简体   繁体   English

不确定为什么我在这个循环中得到Null异常

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

I've got a constructor for a class that iterates over a ArrayList of ImageIcon s, but half way through it crashes with a NullPointerException. 我有一个类的构造函数,它遍历ImageIcon的ArrayList,但是在它的一半时间内崩溃并出现NullPointerException。 Any ideas why? 有什么想法吗?

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

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

I tried throwing GetIcons into a variable and set a breakpoint, it has 8 items (exactly as I expect) but by the time I Step Over my loop 2 or 3 times it crashes. 我尝试将GetIcons抛入一个变量并设置一个断点,它有8个项目(完全符合我的预期)但是当我跳过我的循环2或3次时它会崩溃。 No idea what I'm doing wrong. 不知道我做错了什么。 Newbie to Java. 新手到Java。 Any thoughts? 有什么想法吗?

You have null element/s in the List of ImageIcon s 您在ImageIcon列表中有null元素

You can check for nullity first, 您可以先检查无效,

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

Only if it is ok to skip null elements ie depending on what your app needs. 只有可以跳过null元素,即取决于你的应用程序需要什么。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM