Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - EnumSet.add(enum), throws NullPointerException

This is in Java, cross platform and being debugged on a computer running Ubuntu Oneric with OpenJDK installed as my runtime.

I have an EnumSet for checking inside of in a class in a game I'm working on. I have this readout from logcat, from debug aplenty in my constructor:

Tile : passability being set...?
Exception in thread "Thread-1" javax.media.opengl.GLException:java.lang.NullPointerException
    ...
Caused by: java.lang.NullPointerException
    at net.darkglass.map.Tile.addPassability(Tile.java:144)
    ...

Not amusing. Tracking it down, my problem seems to be, entirely, this line:

public void addPassability(Passability type)
{
    this.passability.add(type);
}

By which I mean the body of that function. It is called from the constructor as:

this.addPassability(Passability.AIR);

When the NullPointerException happens. In the body of the Passability Enum Type, I have

public enum Passability
{
    AIR, ALL, GROUND, NONE, SIGHT, SKILL, STRUCTURE, WATER;
}

as, quite literally, the entire enum save package declaration. this.passability is declared

private EnumSet <Passability> passability;

at the beginning of the class definition and I was under the impression that the add() method was inherited as part of the definition of EnumSet in the Java Standard.

I'm self-taught, but I'm not crazy. Either I've got something wrong or there's a better way to do this. Anyone with some useful knowledge out there able to lend a hand?

like image 992
That Guy Avatar asked Apr 05 '12 16:04

That Guy


1 Answers

So you've declared the passability variable, but you've shown no sign of it being assigned a value other than the default value of null. Perhaps you meant:

private EnumSet<Passability> passability = EnumSet.noneOf(Passability.class);

An EnumSet is an object, like any other - so unless you explicitly give your variable, it will have the default value of null and when you call add on it, you'll get a NullPointerException - which is exactly what's happened here.

like image 70
Jon Skeet Avatar answered Nov 03 '22 00:11

Jon Skeet