java遍历集合过程中删除元素注意的问题

                       java遍历集合过程中删除元素注意的问题

看下面的代码:

public static void main(String args[]) {
    List famous = new ArrayList();
    famous.add("liudehua");
    famous.add("madehua");
    famous.add("liushishi");
    famous.add("tangwei");
    for (String s : famous) {
        if (s.equals("madehua")) {
            famous.remove(s);
        }
    }
}

运行出异常:

java遍历集合过程中删除元素注意的问题_第1张图片

Java新手最容易犯的错误,对JAVA集合进行遍历删除时务必要用迭代器。切记。

其实对于如上for循环,运行过程中还是转换成了如下代码:

for(Iterator it = famous.iterator();it.hasNext();){
         String s = it.next();
         if(s.equals("madehua")){
             famous.remove(s);
             //it.remove();
         }
     }

仍然采用的是迭代器,但删除操作却用了错误的方法。如将famous.remove(s)改成it.remove()

则运行正常,结果也无误。

可以使用 Iterator 本身的方法 remove() 来删除对象, Iterator.remove() 方法会在删除当前迭代对象的同时维护索引的一致性。

Iterator使用通用示例:

Iterator it = list.iterator();
while(it.hasNext()){
    String x = it.next();
    if(x.equals("del")){
        it.remove();
    }
}

 

ArrayList中的Iterator实现:

private class Itr implements Iterator {
   /**
    * Index of element to be returned by subsequent call to next.
    */
   int cursor = 0;
   /**
    * Index of element returned by most recent call to next or
    * previous.  Reset to -1 if this element is deleted by a call
    * to remove.
    */
   int lastRet = -1;
   /**
    * The modCount value that the iterator believes that the backing
    * List should have.  If this expectation is violated, the iterator
    * has detected concurrent modification.
    */
   int expectedModCount = modCount;
   public boolean hasNext() {
           return cursor != size();
   }
   public E next() {
           checkForComodification();
       try {
       E next = get(cursor);
       lastRet = cursor++;
       return next;
       } catch (IndexOutOfBoundsException e) {
       checkForComodification();
       throw new NoSuchElementException();
       }
   }
   public void remove() {
       if (lastRet == -1)
       throw new IllegalStateException();
           checkForComodification();
       try {
       AbstractList.this.remove(lastRet);
       if (lastRet < cursor)
           cursor--;
       lastRet = -1;
       expectedModCount = modCount;
       } catch (IndexOutOfBoundsException e) {
       throw new ConcurrentModificationException();
       }
   }
   final void checkForComodification() {
       if (modCount != expectedModCount)
       throw new ConcurrentModificationException();
   }
   }

总结:

  (1)循环删除list中特定一个元素的,可以使用三种方式中的任意一种,但在使用中要注意上面分析的各个问题。

  (2)循环删除list中多个元素的,应该使用迭代器iterator方式。

 

参考:https://blog.csdn.net/qq_40871196/article/details/98050714

https://www.cnblogs.com/PengChengLi/p/10789066.html

你可能感兴趣的:(Java)