哈希表返回 null 或在键不存在时引发异常



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);

最新更新