简体   繁体   English

添加 ArrayList 元素时如何避免“ConcurrentModificationException”?

[英]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.

相关问题 如果我们在迭代时最后在ArrayList中添加元素,则抛出ConcurrentModificationException - Throwing ConcurrentModificationException if we add elements in ArrayList at the end while iterating 如何在没有concurrentmodificationexception的for循环中向java中的arraylist添加元素 - How to add elements to an arraylist in java inside a for loop without concurrentmodificationexception 迭代并从 ArrayList 中删除元素时如何避免 java.util.ConcurrentModificationException - How to avoid java.util.ConcurrentModificationException when iterating through and removing elements from an ArrayList 迭代此集合时如何避免ConcurrentModificationException? - How to avoid ConcurrentModificationException while iterating this collection? 从ArrayList中删除对象时如何避免ConcurrentModificationException - How to avoid a ConcurrentModificationException when removing objects from an ArrayList 如何在迭代时仅避免ArrayList中的ConcurrentModificationException? - How do I avoid ConcurrentModificationException in ArrayList ONLY when iterating? 在这种情况下如何避免 ConcurrentModificationException? - How to Avoid ConcurrentModificationException in that case? Java ConcurrentModificationException:是否可以在迭代时向哈希表添加元素? - Java ConcurrentModificationException: Is it possible to add elements to a hashtable while iterating through it? For 循环与 Iterator 避免使用 ArrayList 的 ConcurrentModificationException - For loop vs. Iterator to avoid ConcurrentModificationException with an ArrayList 如何在并发线程中操作`values()`和`put()`时避免使用HashMap“ConcurrentModificationException”? - How to avoid HashMap “ConcurrentModificationException” while manipulating `values()` and `put()` in concurrent threads?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM