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?
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.
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.
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.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With