-1

I'm trying to add an item to the ArrayList in a certain order

Iterator<Rating> it = arr.iterator();
while(it.hasNext()){
    Rating o = it.next();
    int index = arr.indexOf(o);
    if(o.getRating() < this.getRating()) {
        arr.add(index, this);
    }
}

I get a ConcurrentModificationException when trying to do it. Is there some simple solution to solve this problem?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • 1
    If you can get a `listIterator()`, by calling add on the iterator. Otherwise: find the index, add element after iteration – knittl May 06 '22 at 19:17

1 Answers1

0

Perhaps one of the following collections will serve in place of the ArrayList?

A CopyOnWriteArrayList will let you write without causing a ConcurrentModificationException. Whether it is a good choice or not depends on the relative frequency of writes to iterations.

Also, consider the PriorityQueue as it will automatically handle ordering, or PriorityBlockingQueue if there are concurrent use considerations.

Phil Freihofner
  • 7,645
  • 1
  • 20
  • 41
  • But even concurrent data structures shouldn't be modified _from the same iterator_ while you are iterating over them. The result might not be, what you expect. – knittl May 07 '22 at 10:27
  • @knittl Did you mean *should be modified from the same iterator*? A ConcurrentModificationException happens if a collection is modified outside of the iterator. If you modify through the iterator, it works fine. – Mark Rotteveel May 07 '22 at 11:50
  • 1
    @MarkRotteveel sorry, I have not expressed myself clearly. You shouldn't modify a collection via collection methods. Calling methods on the iterator is OK (as you have pointed out, thanks!). Modifying them from a different thread is OK for concurrent collections. What you shouldn't do is (simplified): `var iterator = coll.iterator(); while (iterator.hasNext()) { coll.remove(iterator.next()); }` (or add, set, etc.) You will not get an exception, but it almost certainly hints at a flaw in your program or a misunderstanding how collections work (besides the obvious O(n²) behavior in my example). – knittl May 07 '22 at 13:13