在Java中使用LinkedList实现HashSet进行冲突处理时获取NullPointerException?



我正在学习哈希。我在添加功能时遇到问题。 我正在尝试在不使用任何内置哈希表库的情况下设计哈希集。

class MyHashSet {
int setlength = 10000;
LinkedList<Integer>[] hashSet;
/** Initialize your data structure here. */
public MyHashSet() {
LinkedList<Integer>[] hashSet = new LinkedList[setlength];
for (int j=0; j<setlength; j++){
hashSet[j] = new LinkedList<Integer>();
}            
}
public int getHash(int key){
return key%setlength;
}
public void add(int key) {
int hash = getHash(key);
System.out.println("Inside add");
LinkedList<Integer> chain = hashSet[hash];
chain.add(key);
}
}
/**
* MyHashSet object will be instantiated and called as such:
* MyHashSet obj = new MyHashSet();
* obj.add(key);
*/

我在添加函数中收到空指针异常。 通过调试,我得出结论,NPE 出现在 add(( 的第 4 行

LinkedList<Integer> chain = hashSet[hash];

但我不明白为什么?

您的hashSet为 null,因为您没有初始化类的成员变量,而是在构造函数中创建了一个新hashSet。用

/** Initialize your data structure here. */
public MyHashSet() {
hashSet = new LinkedList[setlength];
for (int j=0; j<setlength; j++){
hashSet[j] = new LinkedList<Integer>();
}
}

相反。

(区别:hashSet = new LinkedList[setlength];vsLinkedList<Integer>[] hashSet = new LinkedList[setlength];(

最新更新