在使用 LinkedList 进行冲突处理的 Java 中实现 HashSet 时出现 NullPointerException?
Getting NullPointerException while implementing HashSet in Java using LinkedList for collision handling?
我正在学习哈希。我在添加功能时遇到问题。
我试图在不使用任何内置哈希 table 库的情况下设计一个 HashSet。
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
是空的,因为你没有初始化class的成员变量,而是在你的构造函数中创建了一个新的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];
对比 LinkedList<Integer>[] hashSet = new LinkedList[setlength];
)
我正在学习哈希。我在添加功能时遇到问题。 我试图在不使用任何内置哈希 table 库的情况下设计一个 HashSet。
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
是空的,因为你没有初始化class的成员变量,而是在你的构造函数中创建了一个新的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];
对比 LinkedList<Integer>[] hashSet = new LinkedList[setlength];
)