Java - EnumSet.add (enum), throws a NullPointerException

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

I have an EnumSet for checking inside a class in a game I'm working on. I have this read from logcat, from debugging 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 funny. Tracking this, my problem seems to be completely, this line:

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

By this, I mean the body of this function. It is called from the constructor as:

 this.addPassability(Passability.AIR); 

When a NullPointerException error occurs. In a body like Passability Enum, I have

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

literally, the entire declaration of listing listing. this.passability declared

 private EnumSet <Passability> passability; 

at the beginning of the class definition, and I got the impression that the add () method was inherited as part of the Java standard EnumSet definition.

I’m self-taught, but I’m not crazy. Either I have something wrong, or there is a better way to do this. Anyone who has any useful knowledge can give a hand?

+7
source share
1 answer

So, you declared the passability variable, but you did not indicate that it was assigned a value other than the default value of null . Did you mean:

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

An EnumSet is an object, like any other, so if you have not explicitly specified your variable, it will have a default value of null , and when you call add on it, you will get a NullPointerException - this is exactly what happened here.

+16
source

All Articles