每次发生冲突时,我都会尝试 rehash() 我的 HashTable,但总是收到 Java 堆空间错误。
基本上,我有一个 String[] 表,每次哈希发生冲突时,我都希望将其长度乘以 2。
编辑:我在 while 循环中使用 insert(),该循环将大约 300.000 个单词加载到哈希表中。
public void rehash() {
String[] backup = table;
size = size * 2;
// i get the error on the line below
table = new String[size];
System.out.println("size" + size);
for (int i = 0; i < backup.length; i++) {
if (backup[i] != null) {
insert(backup[i]);
}
}
public void insert(String str) {
int index = hashFunction(str);
if (index > size || table[index] != null) {
rehash();
}
table[index] = str;
}
我的哈希函数:
int val= 0;
val= s.hashCode();
if (val< 0) {
val*= -1;
}
while (val> this.size) {
val%= this.size;
}
return val;
public void load() {
String str = null;
try {
BufferedReader in = new BufferedReader(new FileReader(location));
while ((str = in.readLine()) != null) {
insert(str);
}
in.close();
} catch (Exception e) {
System.out.println("exception");
}
}
最佳答案
从您发布的哈希函数来看,不清楚它返回什么,但看起来有问题。
int index = hashFunction(str);
如果您的索引不正确,那么您的代码会执行大量递归 new String[size]。在此处放置一个计数器或调试点并检查。
if (index > size || table[index] != null) {
rehash();
}
关于java - 为什么在调整 HashTable 实现大小时会出现 OutOfMemoryError 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29582247/