Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't check if int is null

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?

like image 217
Pieter Avatar asked Oct 30 '10 14:10

Pieter


People also ask

How do you check if an int value is null?

So, you can do the check with 0 instead. If you want to do the null check. Use Integer wrapper for that. It's not always a good idea to use an int to represent an identification code since you aren't using it as a true number -- you do no addition nor subtraction or other math operations with it.

Can an int be null?

Java primitive types (such as int , double , or float ) cannot have null values, which you must consider in choosing your result expression and host expression types.

Can int be null C++?

Unlike for pointers, there is no distinct "nulL" value for integers. Given that, your only choice is to store some extra information indicating whether a meaningful value is stored or not.


1 Answers

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");
like image 85
darioo Avatar answered Sep 21 '22 18:09

darioo