List中remove()方法的注意事项

集合中remove注意事项

错误使用:

1、普通for循环遍历List删除指定元素错误

for(int i=0;i<list.size();i++){
          
   
   if(list.get(i)==3) {
          
   
       list.remove(i);
   } 
}
System.out.println(list);

有两个相同且相邻的元素3则只能删除一个,原因是删除一个元素后后造成数组索引左移。这里有一个小细节使用的是**i<list.size()**否则还会造成数组越界问题。

    可以让**remove(i–)**让索引同步调整。 倒序遍历List删除元素

2、使用增强for遍历List删除元素错误

for(Integer i:list){
          
   
    if(i==3) list.remove(i);
}
System.out.println(list);

每次正常执行 remove 方法后,会进行元素个数的比较,都会对执行expectedModCount = modCount赋值,保证两个值相等,那么问题基本上已经清晰了,在 foreach 循环中执行 list.remove(item);,对 list 对象的 modCount 值进行了修改,而 list 对象的迭代器的 expectedModCount 值未进行修改,因此抛出了ConcurrentModificationException异常。

3、迭代遍历,用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);

原理与2相同。

4、List删除元素时,注意Integer类型和int类型的区别

list删除元素时传入的int类型的,默认按索引删除。如果删除的是Integer对象,则调用的是remove(object)方法,删除的是列表对应的元素。

remove正确的用法:

1、倒序循环可解决普通循环删除导致的索引左移问题。

2、顺序循环时,删除当前位置的值,下一个值会补到当前位置,所以需要执行i–操作;

for (int i=0; i<list.size(); i++) {
          
   
        if (list.get(i) == 3) {
          
   
            list.remove(i);
            i--;
        }
    }

3、注意是使用迭代器的remove方法,不要用list的remove方法,不然会抛出异常。

if (null != list && list.size() > 0) {
          
   
    Iterator it = list.iterator();  
    while(it.hasNext()){
          
   
        Student stu = (Student)it.next(); 
        if (stu.getStudentId() == studentId) {
          
   
            it.remove(); //移除该对象
        }
    }
}
经验分享 程序员 微信小程序 职场和发展