【问题标题】:Null Pointer Exception on String Despite Checks [duplicate]尽管检查,字符串上的空指针异常[重复]
【发布时间】:2017-07-23 03:13:08
【问题描述】:

我正在尝试为每个具有模式的单词实现二叉树(例如,你好 - 模式是 ABCCD)

我在它声明的行上不断收到一个空指针异常

    while(pos.getPattern() != null || a){

我不明白为什么 - 有检查。此外,当我打印 pos.getPattern() - 我得到一个字符串不是空值

我真的需要一些帮助

public void AddWord(String word) {
    TreeNode pos = root;
    boolean a = true;
    String pat = PatternMaker.MakePattern(word);
    while(pos.getPattern() != null || a){

        if (pos.getPattern().equals(pat)) {
            WordList list = pos.getList();
            list.insertWord(word);
            pos.setList(list);
            a = true;
        } else if (pat.compareTo(pos.getPattern()) > 0) {
            pos = pos.getRight();
        } else {
            pos= pos.getLeft();

        }
    }
    if(pos ==null){
        pos = new TreeNode(word, pat);
    }
}

【问题讨论】:

  • 看起来pos 在某些情况下可能为空。如果是这样,在 null 对象上调用 getPattern 将抛出 NullPointerException
  • 您尝试使用调试器吗?它将帮助您快速发现哪个对象为空。

标签: java eclipse jakarta-ee


【解决方案1】:

null 值检查树的节点是否为空。您可以表示任何值来表示空节点,但它不应与字符串的值重叠。如果您的集合必须是其他语言的 String 类型,您可以使用 Empty String "" 来表示空值。建议将值保留为 null,因为它可以避免初始化成本并使检查运行得更快。

正如@Teto 解释的那样,getPattern 会在空字符串上抛出空指针。

【讨论】:

    【解决方案2】:

    您需要在while 循环中添加null 检查pos

    在某个时候pos 将在您的while 循环中变为null

    public void AddWord(String word) {
        TreeNode pos = root;
        boolean a = true;
        String pat = PatternMaker.MakePattern(word);
        while((pos!=null && pos.getPattern() != null) || a){
    
            if (pos.getPattern().equals(pat)) {
                WordList list = pos.getList();
                list.insertWord(word);
                pos.setList(list);
                a = true;
            } else if (pat.compareTo(pos.getPattern()) > 0) {
                pos = pos.getRight();
            } else {
                pos= pos.getLeft();
    
            }
        }
        if(pos ==null){
            pos = new TreeNode(word, pat);
        }
    }
    

    希望这会有所帮助!

    【讨论】:

    • 我猜原始海报的意思是在他的 while 循环中包含“if(pos == null)”条件。那会阻止 NPE,它在哪里似乎毫无意义。在退出方法之前立即重新初始化空引用似乎没有什么意义。但也有可能还有其他代码被省略了。
    【解决方案3】:

    你的代码有一行pos = pos.getLeft()。如果该方法返回 null 则调用 pos.getPattern() 将抛出 NPE。

    【讨论】:

    • 谢谢,原来 pos.getLeft() 和 getRight 为空,添加一个检查解决了问题
    猜你喜欢
    • 2017-10-24
    • 2016-07-28
    • 1970-01-01
    • 1970-01-01
    • 2014-04-11
    • 2011-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多