Reputation: 5235
I have an ArrayList
of object containing a reference to their parent object.
I am trying to remove every objects within a specific parent (so equals to the parent object).
If I do:
System.out.println(parent);
my console output:
ParentObject@1f8166e5
if I do:
for(int i = 0; i < array.size(); i++){
if(array.get(i).getParent().equals(parent)){
array.remove(i);
}
}
And (test)
for(int i = 0; i < array.size(); i++){
if(array.get(i).getParent().equals(parent)){
System.out.println(parent + ":" + array.get(i).getParent());
}
}
My console output something like:
ParentObject@1f8166e5:ParentObject@1f8166e5
What's wrong with the snippet above?
Why array.remove(i)
did not work?
Upvotes: 1
Views: 1023
Reputation: 1500665
I suspect the problem is that after you've removed element i
(which moves everything after it up the list - the element at index n + 1
now has index n
etc) you're then skipping the next element. So if you have two consecutive elements to remove, you're missing the second one. The simplest fix is to work from the end:
for (int i = array.size() - 1; i >= 0; i--) {
if (array.get(i).getParent().equals(parent)) {
array.remove(i);
}
}
EDIT: As noted in another answer, it's generally better to use an iterator for removal anyway. In your case, this would look like this:
// We don't know what the Foo type is...
for (Iterator<Foo> iterator = array.iterator(); iterator.hasNext(); ) {
Foo element = iterator.next();
if (element.getParent().equals(parent)) {
iterator.remove(); // Note: *not* array.remove(...)
}
}
Upvotes: 8
Reputation: 3580
You can't remove objects while iterating. You should use Iterator
if you want to remove element while iterating
Upvotes: 1