views:

99

answers:

5

I'm trying to use a dictionary. Whenever I want to check if an element is present in the dictionary, I do this:

int value = results.get("aKeyThatMayOrMayNotBePresent");

if (value != null)
  // ...

But then the compiler says I can't compare an int to a <nulltype>. What's the correct way to check for null in this case?

+1  A: 

int is a primitive type; you can compare a java.lang.Integer to null.

duffymo
+10  A: 

You're comparing a primitive value (int) to null. Since primitives cannot be null, you should use a corresponding object, such as Integer in this case. So, you should write

Integer value = results.get("aKeyThatMayOrMayNotBePresent");
darioo
A: 

Get the Object and check if that is null.

Object valueObj = results.get("...");
if ( valueObj != null )
{
    int value = (int)valueObj;
}
Peter Alexander
+6  A: 

Your null check is too late.

int value = results.get("aKeyThatMayOrMayNotBePresent");

This line already converts the reference to a primitive int. It will throw a NullPointerException if the return value of get is null.

The correct way would be to use Integer instead of int.

Integer value = results.get("aKeyThatMayOrMayNotBePresent");

This way value wont be a primitive type and your null check is valid.

josefx
A: 

You should use Map instead of Dictionary, Dictionary is obsolete.

With Map you can use containsKey() instead, which in my opinion is more readable:

if (results.containsKey(key))
{
    int value = results.get(key);
    [...]
}

In my experience this is not slower than your approach, despite the apparent double access to the map. If this is executed often enough for performance to matter then it is optimized away.

starblue