forEach循环对集合进行循环时,需判断是否为null;


分析forEach的源码会发现:
foreach
源码
例子:

public class Foreach {

    public static void main(String[] args) {
        List<String> strings = new ArrayList<>();
        strings.add("Alis");

        for (String name:strings){
            System.out.println(name);
        }
    }
}

 


用 idea 自带的反编译

public class Foreach {
    public Foreach() {
    }

    public static void main(String[] args) {
        List<String> strings = new ArrayList();
        strings.add("Alis");
        Iterator var2 = strings.iterator();

        while(var2.hasNext()) {
            String name = (String)var2.next();
            System.out.println(name);
        }

    }
}

 

forEach对于集合的遍历实际走的是迭代器的方式(对于数组的遍历这是走的普通的for循环方式), 在进行strings.iterator()时,如果strings为null,就会出现空指针异常,如果strings为空集合,则在判断hasNext()为false,程序不再往下进行,不会出现异常。

测试验证:

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM