为什么这不起作用?

时间:2012-11-21 03:26:11

标签: java

import java.util.*;

class HashingDemo {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);

        System.out.print("Please input the size of the hash table: ");
        int tableSize = keyboard.nextInt();

        LinkedListN[] hashTable = new LinkedListN[tableSize];

        // this works
        LinkedListN list = new LinkedListN();
        list.addToEnd(50);
        System.out.println(list);
        //

        System.out.print("Enter the number of keys to be hashed: ");
        int numberOfKeys = keyboard.nextInt();

        Random randomGenerator = new Random();

        for (int i = 0; i < numberOfKeys; i++) {
            int randomNumber = randomGenerator.nextInt(10000) + 1;

            int location = randomNumber % tableSize;

            hashTable[location].addToEnd(randomNumber);
        }
    }
}

LinkedListN是一个自定义类,(下面附带代码)因为数组不能很好地处理泛型。

但每次运行此程序时,我都会收到以下错误:

Please input the size of the hash table: 10
LinkedListN@5265a77f
Enter the number of keys to be hashed: 20
Exception in thread "main" java.lang.NullPointerException
    at HashingDemo.main(HashingDemo.java:30)

尽管如上所述,如果我只有一个LinkedListN并向其添加数据,那么就没有问题。什么在这里?我已经尝试过并试图弄明白,但我不能。

2 个答案:

答案 0 :(得分:3)

LinkedListN[] hashTable = new LinkedListN[tableSize];只是分配数组,而不是其中的对象。要克服NullPointerException,你必须为每个元素分配对象:

for (int i = 0; i < numberOfKeys; i++) {
    int randomNumber = randomGenerator.nextInt(10000) + 1;
    int location = randomNumber % tableSize;
    if(hashTable[location]==null) {
        hashTable[location] = new LinkedListN();
    }
    hashTable[location].addToEnd(randomNumber);
}

您错过了 hashTable[location] = new LinkedListN();

这一行

答案 1 :(得分:1)

将循环更改为:

for (int i = 0; i < numberOfKeys; i++) {
    int randomNumber = randomGenerator.nextInt(10000) + 1;
    int location = randomNumber % tableSize;

    if(hashTable[location] == null)
        hashTable[location] = new LinkedListN();
    hashTable[location].addToEnd(randomNumber);
}

否则hashTable[location]在您第一次使用它们时将为空。