This question already has an answer here: 這個問題已經在這裏有了答案:
I'm trying to remove some elements from an ArrayList
while iterating it like this: 我正在嘗試從ArrayList
刪除一些元素,同時進行如下迭代:
for (String str : myArrayList) {
if (someCondition) {
myArrayList.remove(str);
}
}
Of course, I get a ConcurrentModificationException
when trying to remove items from the list at the same time when iterating myArrayList
. 當然,當嘗試在迭代myArrayList
的同時從列表中刪除項目時,會收到ConcurrentModificationException
。 Is there some simple solution to solve this problem? 有解決此問題的簡單方法嗎?
#1樓
參考:https://stackoom.com/question/1FPLD/如何在迭代時從-ArrayList-中刪除元素時如何避免-ConcurrentModificationException-重複
#2樓
If you want to modify your List during traversal, then you need to use the Iterator
. 如果要在遍歷期間修改列表,則需要使用Iterator
。 And then you can use iterator.remove()
to remove the elements during traversal. 然後您可以使用iterator.remove()
在遍歷期間刪除元素。
#3樓
Use an Iterator
and call remove()
: 使用Iterator
並調用remove()
:
Iterator<String> iter = myArrayList.iterator();
while (iter.hasNext()) {
String str = iter.next();
if (someCondition)
iter.remove();
}
#4樓
You have to use the iterator's remove() method, which means no enhanced for loop: 您必須使用迭代器的remove()方法,這意味着沒有增強的for循環:
for (final Iterator iterator = myArrayList.iterator(); iterator.hasNext(); ) {
iterator.next();
if (someCondition) {
iterator.remove();
}
}
#5樓
As an alternative to everyone else's answers I've always done something like this: 作爲其他所有人的答案的替代方案,我總是這樣做:
List<String> toRemove = new ArrayList<String>();
for (String str : myArrayList) {
if (someCondition) {
toRemove.add(str);
}
}
myArrayList.removeAll(toRemove);
This will avoid you having to deal with the iterator directly, but requires another list. 這樣可以避免您必須直接處理迭代器,但需要另一個列表。 I've always preferred this route for whatever reason. 無論出於什麼原因,我總是喜歡這條路線。
#6樓
List myArrayList = Collections.synchronizedList(new ArrayList());
//add your elements
myArrayList.add();
myArrayList.add();
myArrayList.add();
synchronized(myArrayList) {
Iterator i = myArrayList.iterator();
while (i.hasNext()){
Object object = i.next();
}
}