-4
\$\begingroup\$

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)) {
            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.

\$\endgroup\$

closed as off-topic by alecxe, Graipher, Vogel612, Nic Hartley, mdfst13 Apr 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.

  • \$\begingroup\$ 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)? \$\endgroup\$ – holroy Apr 19 '17 at 15:54
  • 2
    \$\begingroup\$ Please provide more context. What is d? \$\endgroup\$ – 200_success Apr 19 '17 at 17:21
2
\$\begingroup\$

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) {
    data.add(d);
}
else {
    data[index].incrementCount();
}
\$\endgroup\$
  • \$\begingroup\$ Thank you, but not what I'm looking for. \$\endgroup\$ – user3667111 Apr 19 '17 at 16:48
  • \$\begingroup\$ Oh, I see! I updated the answer! I hope it helps! \$\endgroup\$ – mayo Apr 19 '17 at 17:33

Not the answer you're looking for? Browse other questions tagged or ask your own question.