首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Boolean.valueOf()有时会产生NullPointerException

Boolean.valueOf()有时会产生NullPointerException
EN

Stack Overflow用户
提问于 2017-10-06 16:04:41
回答 1查看 11.3K关注 0票数 115

我有这样的代码:

package tests;

import java.util.Hashtable;

public class Tests {

    public static void main(String[] args) {

        Hashtable<String, Boolean> modifiedItems = new Hashtable<String, Boolean>();

        System.out.println("TEST 1");
        System.out.println(modifiedItems.get("item1")); // Prints null
        System.out.println("TEST 2");
        System.out.println(modifiedItems.get("item1") == null); // Prints true
        System.out.println("TEST 3");
        System.out.println(Boolean.valueOf(null)); // Prints false
        System.out.println("TEST 4");
        System.out.println(Boolean.valueOf(modifiedItems.get("item1"))); // Produces NullPointerException
        System.out.println("FINISHED!"); // Never executed
    }
}

我的问题是,我不明白为什么测试3工作得很好(它打印false,但不产生NullPointerException),而测试4抛出一个NullPointerException。正如您在测试1和测试2中看到的,nullmodifiedItems.get("item1")是equals和null

Java 7和8中的行为是相同的。

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46601104

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档