0

I'm trying to remove every GameObject which meet certain criteria (health<0), completely from every occurrence, so every ArrayList it might be in, and such.

I have a main ArrayList containing every GameObject that may get removed, and I'm trying to iterate through that ArrayList with a For-Each, checking each element for the criteria, and removing it.

This however results in ConcurrentModificationException, which I know the reason to, but do not know how to work around it. Any help would be much appreciated!

Modus Tollens
  • 5,083
  • 3
  • 38
  • 46
patrik1957
  • 67
  • 6
  • 1
    Use iterator to do that as iterator.remove() will not cause taht exception. – Antoniossss Apr 25 '19 at 13:38
  • 5
    See [`Collection#removeIf`](https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/util/Collection.html#removeIf(java.util.function.Predicate)) – Jacob G. Apr 25 '19 at 13:38
  • Just initialize the ArrayList like this: `Collections.synchronizedList(new ArrayList());` – NeplatnyUdaj Apr 25 '19 at 13:39
  • @NeplatnyUdaj this will not solve the problem though – Lino Apr 25 '19 at 14:14
  • @Lino You're right of course, I didn't read carefully. Thought that the issue is from some other thread modifying the array, not that the removal algorithm is wrong from the start. – NeplatnyUdaj Apr 25 '19 at 14:32

2 Answers2

2

As @JacobG. mentioned in his comment, perhaps the "best" way to do this (where "best" is going to be a matter of personal preference) is via the .removeIf() method. Here's an example (which assumes a getHealth() method on your objects):

List<GameObject> gameObjects = new ArrayList<>();

// Some code here to populate the list

gameObjects.removeIf(x -> x.getHealth() < 0);
Jordan
  • 2,273
  • 9
  • 16
0

if you have all the items to be removed in a separate ArrayList, you could use CollectionUtils.subtract() method from apache-commons-collections to remove them from other lists :

yourList = (ArrayList<GameObject>)CollectionUtils.subtract(yourList, listWithObjectsToRemove);

See this link

nullPointer
  • 4,419
  • 1
  • 15
  • 27