0

I was wondering how to access specific elements of objects in an ArrayList using methods, yet I can't seem to get it to work.
I have a Phone object that has an int price and String color, as well as a method that returns the color.

public class Phone

{
private int price;
private String color;

public String getColor()
{
return color;
}

Now let's say I created an array list of Phone objects called phoneCatalog, and added various Phones. How can I count how many phones are red? This is my attempt that isn't working:

int count = 0;

for(int x = 0; x < phoneCatalog.size(); x++)
if((phoneCatalog.get(x)).getColor.equals("red")
count++;
1
  • 1
    if((phoneCatalog.get(x)).getColor.equals("red") should be if(phoneCatalog.get(x).getColor().equals("red") right? what do you mean This is my attempt that isn't working? tell us the problem Commented May 11, 2020 at 12:25

1 Answer 1

2

You need put your count inside your if-statment so that every time the conditon becomes true the value of count will get updated .Like below :

    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 
Sign up to request clarification or add additional context in comments.

2 Comments

Don't want to be a critic but the whole psvm can be replaced with 1 line: long count = Stream.of(new Main(1, "Red"), new Main(...), ...).map(Main::getColor).filter(c -> c.equals("Red")).count();
Didn't know about that .Thanks for your suggestion .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.