【发布时间】:2016-06-01 17:16:23
【问题描述】:
我有 HashMap,我试图根据以下算法从中删除一个元素:
- 当单元格 i 被清空时,需要向前搜索表格的以下单元格,直到找到另一个空单元格或可以移动到单元格 i 的键(即哈希值相等的键)到或早于 i)。
- 当找到一个空单元格时,清空单元格 i 是安全的,删除过程终止。
- 但是,当搜索找到可以移动到单元格 i 的键时,它会执行此移动。以同样的方式继续搜索可移动密钥以查找新的空单元格,直到到达已经为空的单元格而终止。
来源:https://en.wikipedia.org/wiki/Linear_probing#Deletion
这是我现在所拥有的,但是查看我的测试,该实例实际上并没有被删除。你能帮我弄清楚为什么吗?提前致谢
hashFunction() 的结果是计算出来的哈希值。
public class MyHashMap {
Person[] array;
public void remove(Person p) {
int i = hashFunction(p);
while (!p.equals(array[i])) {
i = hashFunction(array[++i]);
}
int b;
while (array[i] != null) {
b = hashFunction(array[++i]);
if (b <= hashFunction(array[i])) {
Person newHash = array[i];
array[i] = null;
array[i++] = newHash;
remove(array[i++]);
}
else if (array[++i] == null) {
array[i] = null;
}
}
}
【问题讨论】:
-
您可能想重新审视 ++i 和 i++ 的使用。 b = hashFunction(数组[++i]); if (b
-
array[i] = null;array[i++] = newHash;这些都分配给同一个元素。