为什么这个数组给出空指针异常?

0 java hash exception

我正在尝试使用哈希表实现一个字典(不使用Java提供的哈希表类,而是从头开始).下面是find()我的Dictionary类中的方法,用于检测插入/删除时键是否在表中.如果密钥已经在表中,则返回与密钥相关联的分数(表中的元素作为密钥/分数对插入到每个表位置的LinkedLists中).如果不是,则返回-1.

我正在运行一个提供的测试程序来确定我的Dictionary类是否有效,但是我遇到了一个NullPointerException到达某一点的时候.以下是特定测试.为什么这个例外会出现?(如果需要,我可以提供更多代码!)

找:

public int find(String config) {
    for (int i = 0; i < dictSize; i++) {
        if (dict[i] != null) {
            LinkedList<DictEntry> current = dict[i];
            String currentConfig = current.peek().getConfig(); //Dictionary.java:66

            if (currentConfig.equals(config)) {
                int currentScore = current.peek().getScore();
                return currentScore;
            }
        }
    }

    return -1;
}
Run Code Online (Sandbox Code Playgroud)

插入:

public int insert(DictEntry pair) throws DictionaryException {
    String entryConfig = pair.getConfig();
    int found = find(entryConfig); //Dictionary.java:27

    if (found != -1) {
        throw new DictionaryException("Pair already in dictionary.");
    }

    int entryPosition = hash(entryConfig);

    if (dict[entryPosition] == null) { //Dictionary.java:35
        LinkedList<DictEntry> list = new LinkedList<DictEntry>();
        dict[entryPosition] = list;
        list.add(pair);
        return 0;
    } else {
        LinkedList<DictEntry> list = dict[entryPosition];
        list.addLast(pair);
        return 1;
    }
}
Run Code Online (Sandbox Code Playgroud)

考试:

    // Test 7: insert 10000 different values into the Dictionary
        // NOTE: Dictionary is of size 9901
    try {
        for (int i = 0; i < 10000; ++i) {
            s = (new Integer(i)).toString();
            for (int j = 0; j < 5; ++j) s += s;
            collisions += dict.insert(new DictEntry(s,i)); //TestDict.java:69
        }
        System.out.println("   Test 7 succeeded");
    } catch (DictionaryException e) {
        System.out.println("***Test 7 failed");
    }
Run Code Online (Sandbox Code Playgroud)

异常堆栈跟踪:

Exception in thread "main" java.lang.NullPointerException
    at Dictionary.find(Dictionary.java:66)
    at Dictionary.insert(Dictionary.java:27)
    at TestDict.main(TestDict.java:69)
Run Code Online (Sandbox Code Playgroud)

小智 5

peek()返回null,这就是原因.您可以在getConfig()调用之前进行无效检查.