繁体   English   中英

从对象的 ArrayList 访问方法

[英]Accessing Methods from ArrayList of Objects

我想知道如何使用方法访问 ArrayList 中对象的特定元素,但我似乎无法让它工作。
我有一个电话 object,它有一个 int 价格和字符串颜色,以及一个返回颜色的方法。

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++;

您需要将您的count放在您的 if 语句中,以便每次条件变为真时,计数的值都会更新。如下所示:

    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);
    }
}

Output

Total Red Color are 3 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM