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,程序不再往下进行,不会出现异常。

 

转载于:https://www.cnblogs.com/xukai-blogs/p/10773186.html

posted @ 2020-08-04 16:25  让我把这一行代码写完  阅读(1393)  评论(0)    收藏  举报