簡體   English   中英

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

[英]How to avoid "ConcurrentModificationException" while add ArrayList elements?

我正在嘗試按特定順序將項目添加到 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);
    }
}

嘗試這樣做時,我得到了一個 ConcurrentModificationException。 有沒有一些簡單的解決方案來解決這個問題?

也許以下 collections 之一將代替ArrayList服務?

CopyOnWriteArrayList將讓您在寫入時不會導致ConcurrentModificationException 它是否是一個好的選擇取決於寫入迭代的相對頻率。

此外,請考慮PriorityQueue ,因為它會自動處理排序,或者如果有並發使用的考慮,請考慮PriorityBlockingQueue

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM