双链接 Lisl 不断出现空指针错误

Doubly Linked Lisl keeps getting null pointer error

我查看了前面的所有示例,看不出我做错了什么。出于某种原因,我真的在与空指针异常作斗争,我只是无法理解它们。

public class DLBDictionary implements DictionaryInterface {
//Store Strings in an Node

public DLBNode firstNode;   

public class DLBNode 
{

    public char value;
    public DLBNode nextValue;
    public DLBNode nextLetter;

    public DLBNode(){
        this.value = '/';
        this.nextValue = null;
        this.nextLetter = null;
    }

    public DLBNode(char value){
        this.value = value;
        this.nextValue = null;
        this.nextLetter = null;         
    }   
}

public DLBDictionary() {
    DLBNode firstNode = new DLBNode('/');   
}

// Add new String to end of list.  If String should come before
// previous last string (i.e. it is out of order) sort the list.
// We are keeping the data sorted in this implementation of
// DictionaryInterface to make searches a bit faster.
public boolean add(String s) {
    int charIndex = 0;              
    while(charIndex<=s.length())
    {
        char currentChar = s.charAt(charIndex);         
        boolean added = false;
        while(!added)
        {
            if(firstNode.value == '/')
            {
                firstNode.value = currentChar;
                added = true;
            }
            else if(firstNode.value == currentChar)
            {
                if(firstNode.nextLetter == null)
                {
                    DLBNode newNode = new DLBNode(); 
                    firstNode.nextLetter = newNode;
                    firstNode = firstNode.nextLetter;
                }
                else
                {
                    firstNode = firstNode.nextLetter;
                }
                added = true;
            }
            else
            {
                firstNode = firstNode.nextValue;
            }
        }           
        charIndex++;
    }
    DLBNode tempNode = new DLBNode('^'); 
    firstNode.nextLetter = tempNode;
    return true;
}

我省略了其余代码,但最后一个 if 语句是我得到异常的地方。对我来说完全是无稽之谈!我不是在构造函数中将 firstNode 的值初始化为 '/' 吗?所以 firstNode.getValue 应该 return '/' 不是空指针异常。

你应该做的 this.firstNode = 新的 DLBNode(); 在 DLBDictionary 的构造函数中。您实际上是在创建一个新对象而不是初始化您的 firstNode。希望对你有帮助。

You reset firstNode with several statements in the loop:

 firstNode = firstNode.nextValue;

所以 firstNode == null 会发生,这会导致 NPE。 char值与它无关,无论如何它都会被初始化为一个值为0x00的字符。