Little gotcha with java auto-boxing

Came across a fun little bit of trivia when dealing with auto-boxing in java. I’m processing content from Cloudgrove and as I examined words I wanted to check if they were in a stop word list. To make this a quick process I have a HashMap<String,Integer> of the stop words. Where the key is the actual word and the value is just 1.

Simple thing to setup. I then added this bit of code to perform the actual test.

if(1 == STOP_WORDS.get(token)){
continue;
}

The problem was that I kept seeing NullPointerExceptions on this line. I checked to make sure that the STOP_WORDS hash was being set up properly and it was. I was a bit perplexed by what was going on . Then I realized that because I was comparing to an int and not an Integer java was trying to auto-box the value. The value would come back as null because the token was not a stop word and then try and convert the null Integer to an int throwing the NullPointerException.

So the moral of the story is that when using auto-boxing you have to be careful about null values. The easy fix was to change the check to:

if(STOP_WORDS.get(token) != null){
continue;
}

and then things worked as expected.