简体   繁体   中英

How to avoid "ConcurrentModificationException" while add ArrayList elements?

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?

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.

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