-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\$
2
  • \$\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
    Commented Apr 19, 2017 at 15:54
  • 2
    \$\begingroup\$ Please provide more context. What is d? \$\endgroup\$ Commented Apr 19, 2017 at 17:21

1 Answer 1

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\$
2
  • \$\begingroup\$ Thank you, but not what I'm looking for. \$\endgroup\$ Commented Apr 19, 2017 at 16:48
  • \$\begingroup\$ Oh, I see! I updated the answer! I hope it helps! \$\endgroup\$
    – mayo
    Commented Apr 19, 2017 at 17:33

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