Home > other >  How to avoid "ConcurrentModificationException" while add ArrayList elements?
How to avoid "ConcurrentModificationException" while add ArrayList elements?

Time:05-07

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?

CodePudding user response:

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.

  • Related