【问题标题】:Hashtable returns null or throws exception when the key is not exist?Hashtable 在 key 不存在时返回 null 或抛出异常?
【发布时间】:2014-12-23 15:08:23
【问题描述】:

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

对于上面的链接,当映射中不存在键时,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而不是抛出异常?

【问题讨论】:

    标签: java dictionary


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2012-12-22
      • 2012-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-27
      • 2016-11-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多