chrisTina
chrisTina

Reputation: 2368

Hashtable returns null or throws exception when the key is not exist?

Java HashMap.get() returns null when I create a new instance of an object as a key

For the above link, it seems that the HashMap returns null when the key is not existed in the map. However when I try:

Map<Integer,Integer> hs = new HashMap<Integer,Integer>();
int value = hs.get(1);
System.out.println(value);

It throws:

Exception in thread "main" java.lang.NullPointerException

What's the issue? How to let the Map returns a null other than throws an exception in such situation?

Upvotes: 2

Views: 2516

Answers (1)

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85779

int is a primitive and doesn't support null value. The code you have there can be understood like this:

Integer temp = hs.get(1);
int value = temp.intValue();
            ^null^

Since this Integer temp variable is null, when performing the auto unboxing to int you have a NullPointerException.

To avoid this problem, use Integer variable, not int:

Map<Integer,Integer> hs = new HashMap<Integer,Integer>();
Integer value = hs.get(1);
System.out.println(value);

Upvotes: 10

Related Questions