# Checking if object is in list [closed]

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

        if (!data.contains(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.

## closed as off-topic by alecxe, Graipher, Vogel612♦, Nic Hartley, mdfst13Apr 20 '17 at 15:51

This question appears to be off-topic. The users who voted to close gave this specific reason:

If this question can be reworded to fit the rules in the help center, please edit the question.

• Not sure how to write in Java, but couldn't you just increase the count within a try..catch statement, and if it fails add it (as it didn't find it already)? – holroy Apr 19 '17 at 15:54
• Please provide more context. What is d? – 200_success Apr 19 '17 at 17:21

You can use indexOf:

Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.

So, you can do this:

int index = data.indexOf(d);
if (index == -1) {