java - 从对象的 ArrayList 访问方法
问题描述
我想知道如何使用方法访问 ArrayList 中对象的特定元素,但我似乎无法让它工作。
我有一个具有 int 价格和字符串颜色的 Phone 对象,以及一个返回颜色的方法。
public class Phone
{
private int price;
private String color;
public String getColor()
{
return color;
}
现在假设我创建了一个名为phoneCatalog 的Phone 对象数组列表,并添加了各种Phone。如何计算有多少手机是红色的?这是我的尝试不起作用:
int count = 0;
for(int x = 0; x < phoneCatalog.size(); x++)
if((phoneCatalog.get(x)).getColor.equals("red")
count++;
解决方案
您需要将您的 if 语句放入您count
的 if 语句中,以便每次条件变为 true 时 count 的值都会更新。如下所示:
public class Main {
private int price;
private String color;
public Main(int price, String color) {
this.price = price;
this.color = color;
}
public String getColor() {
return color;
}
public int getPrice() {
return price;
}
public static void main(String[] args) {
System.out.println("Hello World");
ArrayList < Main > list = new ArrayList < Main > ();
list.add(new Main(1, "Red")); //Adding object in arraylist
list.add(new Main(2, "Blue"));
list.add(new Main(3, "Red"));
list.add(new Main(4, "Red"));
int count = 0;
//looping through values
for (int i = 0; i < list.size(); i++) {
//checking all value in array list
if (list.get(i).getColor().equals("Red")) {
count++;//increment count
}
}
System.out.println("Total Red Color are " + count);
}
}
输出:
Total Red Color are 3
推荐阅读
- java - 需要帮助解决:无法反序列化;嵌套异常是 org.hibernate.type.SerializationException:无法反序列化
- mysql - 如何在 Mysql 中同时更新不同的行
- php - 寻路器打印类作为手风琴的内容
- http - Http 请求和 TCP 连接
- java - BitmapFactory:无法解码流:React Native 的 java.io.FileNotFoundException
- mysql - SQL Query 根据连接的存在有条件地从表中选择一行
- android - 使用支持版本 28.0.0-alpha3 设置错误时 TextInputLayout 提示颜色未更改
- codeigniter - 如何在codeigniter中的数据库中显示dropzone中的图像
- docker - 传感器不会因工人故障而重新安排
- django - 在 DRF 中删除与 PrimaryKeyRelatedField 的多对多关系