不可修改集合中的ConcurrentModificationException [英] ConcurrentModificationException in unmodifiable collection
本文介绍了不可修改集合中的ConcurrentModificationException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有下面的代码,我得到一个ConcurrentModificationException通过执行以下行:
filterCardsToDevice(getCollection ));
代码:
private List< MyClass> filterCardsToDevice(Collection< MyClass> col){
final List< MyClass> newList = new ArrayList< MyClass>();
(MyClass myObj:col){
long id = myObj.getId();
if(id< 0 || id> 0xFFFFFFFF1){
//只是一个日志
} else {
newList.add(myObj);
}
}
return newList;
}
private final Map< Long,MyClass> map = new HashMap< Long,MyClass>();
public Collection< MyClass> getCollection(){
synchronized(map){
return Collections.unmodifiableCollection(map.values());
}
}
堆栈是:
在java.util.HashMap $ HashIterator.nextEntry(HashMap.java:841)
在java.util.HashMap $ ValueIterator.next(HashMap .java:871)
at java.util.Collections $ UnmodifiableCollection $ 1.next(Collections.java:1010)
正确地在foreach行:
for(MyClass myObj:col){
我不明白为什么会出现这个错误,因为我不修改列表。
<
Collections.unmodifiable *
是不复制收集数据,但只能将原始集合包装在特殊的包装器中。因此,如果您修改原始集合,您可能会收到此错误。 如果要创建真正独立的不可修改的集合实例:
Collections.unmodifiableCollection(new ArrayList<>(map.values()));
I have this code below, and I'm getting a ConcurrentModificationException by executing the following line:
filterCardsToDevice(getCollection());
the code:
private List<MyClass> filterCardsToDevice(Collection<MyClass> col) {
final List<MyClass> newList = new ArrayList<MyClass>();
for (MyClass myObj : col) {
long id = myObj.getId();
if (id < 0 || id > 0xFFFFFFFFl) {
// just a log here
} else {
newList.add(myObj);
}
}
return newList;
}
private final Map<Long, MyClass> map = new HashMap<Long, MyClass>();
public Collection<MyClass> getCollection() {
synchronized (map) {
return Collections.unmodifiableCollection(map.values());
}
}
The stack is:
at java.util.HashMap$HashIterator.nextEntry(HashMap.java:841)
at java.util.HashMap$ValueIterator.next(HashMap.java:871)
at java.util.Collections$UnmodifiableCollection$1.next(Collections.java:1010)
Exactly on foreach line:
for (MyClass myObj : col) {
I don't see why this error occurs, because I'm not modifying the list.
解决方案
Be aware, that Collections.unmodifiable*
is not copying collection data, but only wrapping the original collection in a special wrapper. So if you modify the original collection, you can get this error.
If you want to create really independent unmodifiable collection instance:
Collections.unmodifiableCollection(new ArrayList<>(map.values()));
这篇关于不可修改集合中的ConcurrentModificationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文