Java List的remove()方法陷阱

Java List的remove()方法陷阱Java 的 List 在删除元素时 一般会用 list remove o remove i 方法 在使用时 容易触碰陷阱 得到意想不到的结果

首先初始化List,代码如下:

import java.util.ArrayList; import java.util.List; public class ListTest {     public static void main(String[] args) {         List 
  
    list=new ArrayList 
   
     ();         list.add(1);         list.add(2);         list.add(3);         list.add(3);         list.add(4);         System.out.println(list);     } } 
    
  

输出结果为[1, 2, 3, 3, 4]

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

for(int i=0;i 
  

如果这样,删除元素后同步调整索引或者倒序遍历删除元素,是否可行呢?

2、for循环遍历List删除元素时,让索引同步调整–正确!

for(int i=0;i 
  
for(int i=list.size()-1;i>=0;i--){     if(list.get(i)==3){         list.remove(i);     } } System.out.println(list);
for(Integer i:list){     if(i==3) list.remove(i); } System.out.println(list);
public Iterator 
  
    iterator() {     return new Itr(); } Itr 类定义如下: private class Itr implements Iterator 
   
     { int cursor; // index of next element to return int lastRet = -1; // index of last element returned; -1 if no such int expectedModCount = modCount; public boolean hasNext() { return cursor != size; } @SuppressWarnings("unchecked") public E next() { checkForComodification(); int i = cursor; if (i >= size) throw new NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) throw new ConcurrentModificationException(); cursor = i + 1; return (E) elementData[lastRet = i]; } public void remove() { if (lastRet < 0) throw new IllegalStateException(); checkForComodification(); try { ArrayList.this.remove(lastRet); cursor = lastRet; lastRet = -1; expectedModCount = modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } } 
    
  

5、迭代删除List元素–正确!

java中所有的集合对象类型都实现了Iterator接口,遍历时都可以进行迭代:

Iterator 
  
    it = list.iterator(); while (it.hasNext()) { if (it.next() == 3) { it.remove(); } } System.out.println(list); 
  

中需要删除元素时,使用这种方式。

6、迭代遍历,用list.remove(i)方法删除元素–错误!!!

Iterator 
  
    it = list.iterator(); while (it.hasNext()) { Integer value = it.next(); if (value == 3) { list.remove(value); } } System.out.println(list); 
  

上述Integer的list,直接删除元素2,代码如下:

list.remove(2); System.out.println(list);
list.remove(new Integer(2)); System.out.println(list);

   1、用for循环遍历List删除元素时,需要注意索引会左移的问题。

   2、List删除元素时,为避免陷阱,建议使用迭代器iterator的remove方式。

   3、List删除元素时,默认按索引删除,而不是对象删除。

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/221510.html原文链接:https://javaforall.net

(0)
上一篇 2026年3月17日 下午5:56
下一篇 2026年3月17日 下午5:56


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号