Can't check if int is null

2019-06-15 06:57发布

问题:

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:

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");


回答2:

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.



回答3:

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



回答4:

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.



回答5:

Get the Object and check if that is null.

Object valueObj = results.get("...");
if ( valueObj != null )
{
    Integer value = (Integer)valueObj;
}