Skip to main content
1 of 2

checking if object in list

Using the contains method I'm checking to see if an object is in an arraylist, if its not then I add it else I want to increment the count.

        if (!data.contains(d)) {
            data.add(d);
        } else {
            for (int j = 0; j < data.size(); j++) {
                if (data.get(j).equals(d)) {
                    data.get(j).incrementCount();
                }
            }
        }

I'm looking at the code I've written and it looks wasteful, having to loop through the arraylist multiple times, I was thinking about using booleans but was wondering if there is any other way.