使用Iterator的方式可以顺利删除和遍历
Iterator<String> it = list.iterator();
while(it.hasNext()){
String x = it.next();
if(x.equals("del")){
it.remove();
}
}
这种方式可以正常的循环及删除。但要注意的是,使用iterator的remove方法,如果用list的remove方法同样会
报上面提到的ConcurrentModificationException错误。
迭代器iterator的remove()方法不仅会删除元素,还会维护一个标志,用来记录目前是不是可删除状态。例
如,你不能连续两次调用它的remove()方法,调用之前至少有一次next()方法的调用。但是要注意的是:
list.remove()只是删除元素,可是不会改变原有元素的位置。比如有 0 1 2 3 4 5这六个元素,我删除掉3这
个元素,则4还是处于第四个位置,不会跳到第三个位置。
4.用一个List 记录要删除的数据,最后removeAll(List);
List<Integer> removeList = new ArrayList()
for(Integer i : intList)
{
if(i == 13)
{
removeList.add(i);
}
}
//最后
if(removeList.size()>0)
{
intList.removeAll(removeList);
}