• 【Java基础】增强for循环要注意陷阱


    什么是增强for循环

      增强for循环是一种简单模式的for循环,为了方便数组和集合的遍历而存在。

            int[] arr = new int[]{1, 2, 3, 4, 5, 6};
            for (int a : arr) {
                System.out.println(a);
            }
    
            ArrayList<Integer> list = new ArrayList();
            list.add(1);
            list.add(2);
            list.add(3);
            list.add(4);
            list.add(5);
            list.add(6);
            for (int i : list) {
                System.out.println(i);
            }

    增强for循环的原理

      对于集合的遍历,增强for循环其实内部是通过迭代器实现的,可以做一个简单的验证,我们知道在迭代器中,迭代的时候不允许修改,不然会抛出ConcurrentModificationException异常,那我们不妨在增强型for循环中也尝试去修改集合中的对象,看是否抛出同样的异常。

            ArrayList<Integer> list = new ArrayList();
            list.add(1);
            list.add(2);
            list.add(3);
            list.add(4);
            list.add(5);
            list.add(6);
            for (int i : list) {
                if(i == 4)list.add(1024);
                System.out.println(i);
            }

    将上述集合for循环遍历中加入一行add对象的代码,运行确实会抛出异常。抛出的异常如下:

    Exception in thread "main" java.util.ConcurrentModificationException
        at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:859)
        at java.util.ArrayList$Itr.next(ArrayList.java:831)
        at Test.main(Test.java:41)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)
        at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)

    从上述异常的描述中可以看出,其中的确调用了Itr.next方法,所以内部是通过Iterator实现遍历的。

    慎用增强型for循环之可能陷阱

    1. 增强型for循环不支持遍历时修改
    2. 使用增强型for循环时,对遍历的集合需要做null判断,不然可能引发空指针异常。
  • 相关阅读:
    linux系统telnet端口不通能收到SYN但不回SYN+ACK响应问题排查(转载)
    leveldb
    SSTable and Log Structured Storage: LevelDB
    fio terse输出详解
    bash的循环中无法保存变量
    怎样当好一个师长
    共享变量的并发读写
    Storage Systems topics and related papers
    Storage System and File System Courses
    调试std::string
  • 原文地址:https://www.cnblogs.com/gslyyq/p/4969170.html
Copyright © 2020-2023  润新知