原始list:[1,2,3,3,4]
1.普通for循环遍历List删除指定元素-------错误
for (int i=0;i<list.size();i++){
if(list.get(i)==3) list.remove(i);
}
System.out.println(list);
//输出结果: [1,2,3,4]
元素3只删除了一个,是因为remove(index)会移除index位置上的元素,index之后的元素会全部依次左移,即索引依次 -1要保证能操作所有的数据,需要在移除元素的同时把index-1,否则原来的索引为 index+1 的元素就无法遍历到(因为原来索引为 index+1 的数据在执行移除操作后,索引变成 index)
解决1:for 循环遍历 List 删除元素时,让索引同步调整
for(int i=0;i<list.size();i++){
if(list.get(i)==3) list.remove(i--);
}
System.out.println(list);
//输出结果:[1, 2, 4]
解决2:倒序遍历 List 删除元素
for(int i=list.size()-1;i>=0;i--){
if(list.get(i)==3) list.remove(i);
}
System.out.println(list);
//输出结果:[1, 2, 4]
2.迭代遍历,用 list.remove(i)方法删除元素------错误
Iterator<Integer> it=list.iterator();
while(it.hasNext()){
Integer value=it.next();
if(value==3){
list.remove(value);
}
}
System.out.println(list);
//抛出异常:java.util.ConcurrentModificationException
3.foreach 遍历 List 删除元素 ------错误
for(Integer i:list){
if(i==3) list.remove(i);
}
抛出异常:java.util.ConcurrentModificationException
解决:迭代删除 List 元素
Iterator<Integer> it=list.iterator();
while(it.hasNext()){
if(it.next()==3){
it.remove();
}
}
System.out.println(list);
//输出结果:[1, 2, 4]
推荐:Iterator.remove()方法会在删除当前迭代对象的同时,保留原来元素的索引。
错误2 3 的原理相同,但我没看懂它的原理,还是记住吧。
4. List 删除元素时,注意Integer类型和int类型的区别.
list 删除元素时 默认按索引删除,如果需要删除Integer 对象,调用remove(object)方法,如下:
//删除 数字 2,而不是删除 位置为2的元素
list.remove(new Integer(2));