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

测试验证:

 

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

相关文章:

  • 2021-11-08
  • 2022-12-23
  • 2022-12-23
  • 2021-06-11
  • 2021-07-05
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-08-03
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-09
  • 2022-12-23
相关资源
相似解决方案