【问题标题】:Java delete element from hashmapJava 从哈希图中删除元素
【发布时间】:2016-06-01 17:16:23
【问题描述】:

我有 HashMap,我试图根据以下算法从中删除一个元素:

  1. 当单元格 i 被清空时,需要向前搜索表格的以下单元格,直到找到另一个空单元格或可以移动到单元格 i 的键(即哈希值相等的键)到或早于 i)。
  2. 当找到一个空单元格时,清空单元格 i 是安全的,删除过程终止。
  3. 但是,当搜索找到可以移动到单元格 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;这些都分配给同一个元素。

标签: java hashmap


【解决方案1】:

您的后增量和前增量运算符看起来会导致您的问题。例如,

array[i] = null;
array[i++] = newHash;

在这里,您将null 分配给array[i],然后在i 递增之前再次将newHash 分配给array[i]。您实际上会想使用++i 而不是i++

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-13
    • 2013-11-09
    • 1970-01-01
    • 2011-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多