1

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?

1
  • What is the indication that remove() doesn't work? Commented Jan 30, 2014 at 21:30

2 Answers 2

8

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(...)
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

@Pier-AlexandreBouchard: Not shuffle in terms of "randomly reassign" but shuffle as in "everything else moves up one place" - if you had an element A with index 10, and you remove the element at index 2, element A now has index 9.
1

You can't remove objects while iterating. You should use Iterator if you want to remove element while iterating

2 Comments

He is not using an Iterator but an indexed for loop. Removing works, it is just not a good pattern and may lead to problems as @Jon Skeet hinted.
I've added an Iterator-based approach to my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.