我正在研究哈希。我在使用添加功能时遇到麻烦。我试图在不使用任何内置哈希表库的情况下设计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);
*/
我在add函数中得到了Null指针异常。通过调试,我得出的结论是NPE在add()的第4行中出现
LinkedList<Integer> chain = hashSet[hash];
但是我不明白为什么?
我正在研究哈希。我在使用添加功能时遇到麻烦。我试图在不使用任何内置哈希表库的情况下设计HashSet。类MyHashSet {int setlength = 10000; ...
您的hashSet
为空,因为您没有初始化该类的成员变量,而是在构造函数中创建了一个新的hashSet
。使用