gpt4 book ai didi

java - 为什么这不起作用?

转载 作者:行者123 更新时间:2023-12-01 18:57:21 26 4
gpt4 key购买 nike

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 并向其中添加数据,就没有问题。这是怎么回事?我一直在尝试解决这个问题,但我做不到。

最佳答案

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

关于java - 为什么这不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13485873/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com