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