8

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?

That Guy
  • 103
  • 1
  • 8
  • could you show more chunks of your code. All I see if a line here and there. – Adrian Apr 05 '12 at 16:13
  • Jon Skeet has it. I never initialized it because I'm so used to only using primitives ~ I try to KISS my work because it keeps things sane. – That Guy Apr 05 '12 at 16:25

1 Answers1

17

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Yes sir, that works just fine. However, I have some concern on that note. Right now, that's added to the field declaration ~ is it _really_ safe there, or should I move it down to my constructor call? That is, `private EnumSet passability;` up above and `this.passability = EnumSet.noneOf(Passability.class);` in the body of the constructor? – That Guy Apr 05 '12 at 16:28
  • 2
    @ThatGuy: It's fine. They're pretty much equivalent. – Jon Skeet Apr 05 '12 at 16:29