如何从二进制搜索树中的可比较接口修复空指​​针异常

时间:2019-04-28 17:28:03

标签: java nullpointerexception

在我的二叉搜索树程序中,在我的main方法中向该树添加对象后出现错误。这导致我的Comparable实现出现了Null Pointer异常。我的程序将莫尔斯电码字符放在二进制搜索树中,因此我试图按字典顺序按对象的代码值比较对象。为什么这行不通?

public class MorseCharacter implements Comparable<MorseCharacter> {

private String code;
private char letter;

    public int compareTo(MorseCharacter morseCharacter) {

    String code1 = this.code;
    String code2 = morseCharacter.getCode();

    return code1.compareTo(code2);
}

    public int hashCode() {
    int hashVal = 0;

    for (int i=0; i<code.length();i++) {
        hashVal = (hashVal*31 +code.charAt(i));
    }

    return hashVal;
}

public boolean equals(Object obj) {
    if (this == obj) {
        return true;
    }

    if (obj == null) {
        return false;
    }

    else {
        return (this.hashCode() == obj.hashCode());
        }   

}

这是主要方法中的部分。我正在从文件中解析数据,已检查并正确读取了该数据。

        try {
        reader = new BufferedReader(new FileReader(file));
        String line = reader.readLine();


        while (line != null) {

            String[] output = line.split(" ");
            String letter = output[0];
            MorseCharacter morseCharacter = new MorseCharacter(letter.charAt(0), output[1]);
            BSTElement<String, MorseCharacter> bstElement = new BSTElement(letter, morseCharacter);
            tree.add(bstElement);
            line = reader.readLine();
        }
        reader.close();

这是错误消息:

Exception in thread "main" java.lang.NullPointerException: The object you are comparing to is null.
at bridges.base.Element.compareTo(Element.java:207)
at MorseCodeTree.add(MorseCodeTree.java:86)
at MorseCodeTree.main(MorseCodeTree.java:220)

更改为compareTo方法(未修复):

public int compareTo(MorseCharacter morseCharacter) {

    if (this.code == null) {
        return 0; 
    }

    return this.code.compareTo(morseCharacter.getCode());
}

0 个答案:

没有答案