我不断收到并发修改异常
String[] permsList = Constants.CUST_MKT_PERMS_FIELDS;
String hiddenFieldVector = new Vector<String>(permsList.length);
Iterator<String> itr = hiddenFieldVector.iterator();
for(int i = 0; i < arrayLength; i++){ //arrayLength is never null or 0
...a lot of code...
String target = fromDatabase(); //this is never null
while(itr.hasNext() && hiddenFieldVector.contains(target)){
hiddenFieldVector.remove(target);
Logger.debug("itr.next() = " + itr.next());
}
...a lot of code...
}
有什么想法吗?
当前解决方案:
while(itr.hasNext() && hiddenFieldVector.contains(target) && (itr.next().equals(target))){
itr.remove();
Logger.debug("itr.next() = " + itr.next());
}
hiddenFieldVector.remove(target);
循环时不要在list
上呼叫remove
。循环时修改列表会抛出ConcurrentModificationException
.
使用 iterator
并在 iterator
上呼叫 remove
而不是 list
。
例:
while(itr.hasNext() && hiddenFieldVector.contains(target)){
itr.remove();
Logger.debug("itr.next() = " + itr.next());
}