简体   繁体   中英

How to find the number of times a specific element occurs in an Array list in Java

I have written a method with the aim to count the number of times a specific flavour of crisps appears in a snack machine in blueJ

public int countPacks(String flavour){

        int n = 0;
        int nrFlavour = 0;
        while( n < packets.size()) {
            if( packets.get(n).equals(flavour)){
                nrFlavour++;
                n++;
            }
            else n++;
        }
        return nrFlavour;
}

I have an Arraylist 'packets' which holds PackOfCrisps objects which have a specific flavour. However when I have added say three packets of "salt" flavour crisps and I run this method, inputting "salt" as the flavour, it just returns 0 as though there are no PackOfCrisps objects with flavour "salt". Sorry if this doesn't make sense. I am very new to Java and I have tried to explain my problem the best I can. :)

The list packets holds PackOfCrisps objects, and the method takes a String parameter. So the statement packets.get(n).equals(flavour) is comparing a PackOfCrisps object to a String , hence the count variable will never increase.

You need to compare the flavour string to the specific field of the object, something like:

if(packets.get(n).getFlavour().equals(flavour)){

On a side note, you can replace the while loop with a simple for loop and remove the increment of n .

There is a built-in solution to your problem, you can use this method

You can rewrite your countPacks method like this :

public int countPacks(String flavour){
    return Collections.frequency(packets, flavour);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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