简体   繁体   中英

remove specific object does not work in Java ArrayList

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?

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(...)
    }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM