[英]How to avoid "ConcurrentModificationException" while add ArrayList elements?
I'm trying to add an item to the ArrayList in a certain order我正在尝试按特定顺序将项目添加到 ArrayList
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.尝试这样做时,我得到了一个 ConcurrentModificationException。 Is there some simple solution to solve this problem?
有没有一些简单的解决方案来解决这个问题?
Perhaps one of the following collections will serve in place of the ArrayList
?也许以下 collections 之一将代替
ArrayList
服务?
A CopyOnWriteArrayList will let you write without causing a ConcurrentModificationException
. CopyOnWriteArrayList将让您在写入时不会导致
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.此外,请考虑PriorityQueue ,因为它会自动处理排序,或者如果有并发使用的考虑,请考虑PriorityBlockingQueue 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.