zoukankan      html  css  js  c++  java
  • 集合遍历的时候删除List

    在Java中有时候我们会需要对List里面的符合某种业务的数据进行删除,但是如果不了解里面的机制就容易掉入“陷阱”导致遗漏或者程序异常。本文以代码例子的方式进行说明该问题。

    1、采用索引下标遍历的方式

    我们看这段示例代码:

    1    public class ListRemoveTest {
    2    
    3        public static void main(String[] args) {
    4            List<Integer> list = new ArrayList<Integer>();
    5            list.add(1);
    6            list.add(2);
    7            list.add(2);
    8            list.add(3);
    9            list.add(4);
    10    
    11            for (int i = 0; i < list.size(); i++) {
    12                if (2 == list.get(i)) {
    13                    list.remove(i);
    14                }
    15                System.out.println(list.get(i));
    16            }
    17            System.out.println("最后结果=" + list.toString());
    18        }
    19    }

    该代码运行结果如下:

    1
    2
    3
    4
    最后结果=[1, 2, 3, 4]

    我们是想删除等于2的元素,但结果显示只删除了一个2,另一个2被遗漏了,原因是:删除了第一个2后,集合里的元素个数减1,后面的元素往前移了1位,导致了第二个2被遗漏了。

    2、采用For循环遍历的方式

    1  public class ListRemoveTest {
    2    
    3        public static void main(String[] args) {
    4            List<Integer> list = new ArrayList<Integer>();
    5            list.add(1);
    6            list.add(2);
    7            list.add(2);
    8            list.add(3);
    9            list.add(4);
    10    
    11            for (Integer value : list) {
    12                if (2 == value) {
    13                    list.remove(value);
    14                }
    15                System.out.println(value);
    16            }
    17            System.out.println("最后结果=" + list.toString());
    18        }
    19    }
     

    程序运行结果:

    1
    2
    Exception in thread “main” java.util.ConcurrentModificationException
    at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)
    at java.util.AbstractList$Itr.next(AbstractList.java:343)
    at ListRemoveTest.main(ListRemoveTest.java:32)

    从运行结果看到程序抛ConcurrentModificationException。

    JDK的API中对该异常描述道:

    public class ConcurrentModificationException extends RuntimeException当方法检测到对象的并发修改,但不允许这种修改时,抛出此异常。
    例如,某个线程在 Collection 上进行迭代时,通常不允许另一个线性修改该 Collection。通常在这些情况下,迭代的结果是不确定的。如果检测到这种行为,一些迭代器实现(包括 JRE 提供的所有通用 collection 实现)可能选择抛出此异常。执行该操作的迭代器称为快速失败 迭代器,因为迭代器很快就完全失败,而不会冒着在将来某个时间任意发生不确定行为的风险。
    注意,此异常不会始终指出对象已经由不同 线程并发修改。如果单线程发出违反对象协定的方法调用序列,则该对象可能抛出此异常。例如,如果线程使用快速失败迭代器在 collection 上迭代时直接修改该 collection,则迭代器将抛出此异常。
    注意,迭代器的快速失败行为无法得到保证,因为一般来说,不可能对是否出现不同步并发修改做出任何硬性保证。快速失败操作会尽最大努力抛出 ConcurrentModificationException。因此,为提高此类操作的正确性而编写一个依赖于此异常的程序是错误的做法,正确做法是:ConcurrentModificationException 应该仅用于检测 bug。

    Java中的For each实际上使用的是iterator进行处理的。而iterator是不允许集合在iterator使用期间删除的。所以导致了iterator抛出了ConcurrentModificationException 。

    3、在遍历List过程中删除元素的正确做法

        1    public class ListRemoveTest {
            2     
            3        public static void main(String[] args) {
            4            List<Integer> list = new ArrayList<Integer>();
            5            list.add(1);
            6            list.add(2);
            7            list.add(2);
            8            list.add(3);
            9            list.add(4);
            10     
            11            Iterator<Integer> it = list.iterator();
            12            while (it.hasNext()) {
            13                Integer value = it.next();
            14                if (2 == value) {
            15                    it.remove();
            16                }
            17                System.out.println(value);
            18            }
            19            System.out.println("最后结果=" + list.toString());
            20        }
            21    }
     

    输出结果:

    1
    2
    2
    3
    4
    最后结果=[1, 3, 4]

    我们看到两个2全部被删除了,最后结果剩下1,3,4完全正确。

    但对于iterator的remove()方法,也有需要我们注意的地方:

    1、每调用一次iterator.next()方法,只能调用一次remove()方法。

    2、调用remove()方法前,必须调用过一次next()方法。

    以下是JDK-API中对于remove()方法的描述:

    void remove()

    从迭代器指向的集合中移除迭代器返回的最后一个元素(可选操作)。每次调用 next 只能调用一次此方法。如果进行迭代时用调用此方法之外的其他方式修改了该迭代器所指向的集合,则迭代器的行为是不明确的。

    抛出:UnsupportedOperationException - 如果迭代器不支持 remove 操作。IllegalStateException - 如果尚未调用 next 方法,或者在上一次调用 next 方法之后已经调用了remove 方法。

  • 相关阅读:
    姐姐的vue(1)
    LeetCode 64. Minimum Path Sum 20170515
    LeetCode 56. 56. Merge Intervals 20170508
    LeetCode 26. Remove Duplicates from Sorted Array
    LeetCode 24. Swap Nodes in Pairs 20170424
    LeetCode 19. Remove Nth Node From End of List 20170417
    LeetCode No.9 Palindrome Number 20170410
    LeetCode No.8. String to Integer (atoi) 2017/4/10(补上一周)
    LeetCode No.7 Reverse Integer 2017/3/27
    LeetCode No.4 Median of Two Sorted Arrays 20170319
  • 原文地址:https://www.cnblogs.com/Wen-yu-jing/p/4274107.html
Copyright © 2011-2022 走看看