简体   繁体   中英

Why won't this work?

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 is a custom class, (code attached below) because arrays don't handle generics too well.

But every time I run this program I get the following error:

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)

Even though as I commented above, if I just have a single LinkedListN and add data to it, there's no issue. What's up here? I've tried and tried to figure it out, but I cannot.

LinkedListN[] hashTable = new LinkedListN[tableSize]; just allocates the array, not the objects inside it. To overcome the NullPointerException you have to allocate object for each element:

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);
}

you have missed the line hashTable[location] = new LinkedListN();

Change the loop to:

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);
}

Otherwise the hashTable[location] s will be null when you first use them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM