I am trying to check whether a key is in a map(Java) and am a bit confused about why one of my solutions works and the other doesn't.
In particular: when I compare myMap.get(s)
directly to null
it works but when I first save myMap.get(s)
to a variable (number
) and then compare to null
it throws a The operator != is undefined for the argument type(s) int, null
error.
Code that works:
import java.util.*;
import java.io.*;
class test1{
public static void main(String []argh){
// Create a map
Map<String, Integer> myMap;
myMap = new HashMap<String, Integer>();
// Make an entry in the map
String key = "hello";
int value = 5;
myMap.put(key, value);
String s = "hi";
if (myMap.get(s) != null)
{
int number = myMap.get(s);
System.out.printf("%s\n", number);
}else
{
System.out.println("Not in dict");
}
}
}
Code that does not work:
import java.util.*;
import java.io.*;
class test2{
public static void main(String []argh){
// Create a map
Map<String, Integer> myMap;
myMap = new HashMap<String, Integer>();
// Make an entry in the map
String key = "hello";
int value = 5;
myMap.put(key, value);
String s = "hi";
int number = myMap.get(s);
if (number != null)
{
System.out.printf("%s\n", number);
}else
{
System.out.println("Not in dict");
}
}
}
I would like to know how I am supposed to understand this, because to me myMap.get(s)
is also just an int?
Thanks for reading.