迭代集合删除问题
2008-01-26 08:47
246 查看
迭代出错:在循环删除一个集合的数据时,不能用Collection .remove
得用Iterator .remove才行
删除对象后,集合会重新排序,会导致发生异常
正确写法:
String str = null;
while (it.hasNext()) {
str = (String) it.next();
if (deliverySet.contains(str)) {
it.remove();
} else {
tempMap.put(str, "1"); }
}
以下写法就会出现异常情况:
String str = null;
while (it.hasNext()) {
str = (String) it.next();
if (deliverySet.contains(str)) {
deliverySet.remove(str);
} else {
tempMap.put(str, "1");
}
}
得用Iterator .remove才行
删除对象后,集合会重新排序,会导致发生异常
正确写法:
String str = null;
while (it.hasNext()) {
str = (String) it.next();
if (deliverySet.contains(str)) {
it.remove();
} else {
tempMap.put(str, "1"); }
}
以下写法就会出现异常情况:
String str = null;
while (it.hasNext()) {
str = (String) it.next();
if (deliverySet.contains(str)) {
deliverySet.remove(str);
} else {
tempMap.put(str, "1");
}
}
相关文章推荐
- 关于迭代集合同时删除元素报错的问题java.util.ConcurrentModificationException
- 集合foreach循环和三种迭代的删除
- 删除正在循环迭代的集合元素的分析
- list集合删除问题
- Java-集合 list对象进行指定位置插入、删除、迭代、遍历输出(具体习题讲解)
- ArrayList的迭代删除问题
- 问题1:集合不能一边遍历一边删除
- 关于java进行迭代时更改迭代集合的问题
- Python 迭代删除重复项,集合删除重复项
- Hibernate 删除对象关联集合遇到的问题
- MyBatis foreach标签循环迭代集合对象实现批量删除
- map中的迭代删除操作注意问题
- Java-集合 list对象进行指定位置插入、删除、迭代、遍历输出(具体习题讲解)
- ArrayList迭代过程删除问题
- 为什么Iterator的remove方法可保证从源集合中安全地删除对象,而在迭代期间不能直接删除集合内元素
- java集合迭代删除,一个很诡异的现象
- 集合已修改;枚举操作可能无法执行。使用foreach 循环删除DataRow的时候的问题! 该死的AcceptChanges() Row.elete() Remove(Row)使用不同。
- JAVA循环迭代中删除或添加集合数据报java.util.ConcurrentModificationException错误
- Iterator遍历集合时不可以删除集合中的元素问题
- java集合循环中删除元素问题以List集合为例