Java HashMap.get(( 当我创建对象的新实例作为键时返回 null
对于上面的链接,当映射中不存在键时,HashMap
似乎返回 null。但是当我尝试时:
Map<Integer,Integer> hs = new HashMap<Integer,Integer>();
int value = hs.get(1);
System.out.println(value);
它抛出:
Exception in thread "main" java.lang.NullPointerException
问题出在哪里?在这种情况下,如何让Map
返回 null 而不是抛出异常?
int
是一个原语,不支持null
值。您那里的代码可以这样理解:
Integer temp = hs.get(1);
int value = temp.intValue();
^null^
由于这个Integer temp
变量是 null
,因此在执行自动拆箱以int
时,您有一个NullPointerException
。
若要避免此问题,请使用变量Integer
而不是int
:
Map<Integer,Integer> hs = new HashMap<Integer,Integer>();
Integer value = hs.get(1);
System.out.println(value);