簡體   English   中英

不確定為什么我在這個循環中得到Null異常

[英]Unsure why I'm getting a Null exception in this loop

我有一個類的構造函數,它遍歷ImageIcon的ArrayList,但是在它的一半時間內崩潰並出現NullPointerException。 有什么想法嗎?

for (ImageIcon i : dm.GetIcons())
{
    _labels.add(new JLabel(i));
}

public ArrayList<ImageIcon> GetIcons(){
    return _icons;  
}

我嘗試將GetIcons拋入一個變量並設置一個斷點,它有8個項目(完全符合我的預期)但是當我跳過我的循環2或3次時它會崩潰。 不知道我做錯了什么。 新手到Java。 有什么想法嗎?

您在ImageIcon列表中有null元素

您可以先檢查無效,

for (ImageIcon i : dm.GetIcons())
{
    if (i != null) {
        _labels.add(new JLabel(i));
    }
}

只有可以跳過null元素,即取決於你的應用程序需要什么。

您的ImageIcon ArrayList可能包含一些空對象或沒有值的Empty對象

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM