java - 哈希表和多元素线性探测的解决方案

标签 java hashtable linear-probing

我正在尝试编写一种在处理多个“动物”的哈希表中进行线性探测的解决方案,类似于下面给我的解决方案。

index++;
if(index == hashAnimals.length) {
    index = 0;
}
if(hashAnimals[index] == null){
    hashAnimals[index] = new Animal(animals.get(i));
}

但有人告诉我,这只是针对一只动物、处于一种位置的解决方案。这就是我目前针对多种动物开始的解决方案:

int index = 0;
for(int i = 0; i < hashAnimals.length) {
    if(index = hashAnimals.length){
        index = 0;
    }

但是我在考虑寻找免费职位的解决方案时遇到了问题。我应该使用另一个 for 循环吗?如果我只是在代码中复制上面的第二个 if 语句,我相信如果索引已被采用,我尝试添加的“动物”将被跳过,并且“i”将在末尾增加到下一个动物循环。

最佳答案

一般来说,线性探测从哈希函数提供的索引开始,然后寻找最接近的空单元格索引。

确实没有必要有一个特殊的包裹式保护壳。使用模运算符要容易得多。

Animal[] hashTable = new Animal[SIZE];

void put(Animal animal) {
    for (int i = 0; i < SIZE; i++) {
        int index = (animal.hashCode() + i ) % SIZE;
        if (hashTable[index] == null) {
            hashTable[index] = animal;
            return;
        }
    }
    throw new IllegalStateException("No empty cells in hash table");
}

关于java - 哈希表和多元素线性探测的解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47503797/

相关文章:

Powershell:通过哈希表计算唯一字符串

c++ - 在用户定义的对象上调用 std::find 时出错

java - 为什么二次探测无法在下一次插入时找到位置,而线性探测总是能找到一个位置?

java - 在java中制作一个可播放的jslider

java - Java 如何对 HashMap 或 HashTable 中的项目进行排序?

java - 如何在 Java 中更改 RadioGroup 的颜色

algorithm - 散列中的聚类(在碰撞中)是什么意思?

java.lang.NumberFormatException : null in Integer. parseInt

java - 相对于 JFrame 移动组件