user2977590
user2977590

Reputation: 9

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 ImageIcons, but half way through it crashes with a 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. No idea what I'm doing wrong. Newbie to Java. Any thoughts?

Upvotes: 0

Views: 68

Answers (2)

SSB
SSB

Reputation: 144

your ImageIcon ArrayList might have some null objects or a Empty object with no values

Upvotes: 0

setzamora
setzamora

Reputation: 3640

You have null element/s in the List of ImageIcons

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 i.e. depending on what your app needs.

Upvotes: 2

Related Questions