双重哈希哈希表的get方法出错



我有下面的方法来获取在双哈希类中输入的键的值。它在运行后一直说有错误。

 /* Function to get value of a key */
 public int get(String key) 
 {
    int hash1 = myhash1( key );
    int hash2 = myhash2( key );
    while (table[hash1] != null && !table[hash1].key.equals(key))
    {
        hash1 += hash2;
        hash1 %= TABLE_SIZE;
    }
    return table[hash1].value;
}

首先,我必须在哈希表中插入一个新的名称和值,如果之后我有示例:

    System.out.println( "Please enter the name of the person you want to search for: " );
    System.out.println( "Value= " + ht.get(scan.next()));

但如果我有:

    System.out.println( "Please enter the name of the person you want to search for: " );
    System.out.println( "Value= " + ht.get(scan.nextLine()));

上面说有个错误。这意味着该方法不接受包含空格等的整行字符串,而只接受单个字符串。Netbeans表示错误出现在以下行:

return table[hash1].value;

有人能帮我吗?

退出循环的条件之一是

while (table[hash1] != null

这意味着您知道表[hash1]可能是null,但您随后执行

return table[hash1].value;

然后会得到一个NullPointerException。这对于调试器来说是显而易见的。

我建议你在尝试像一样使用之前先检查一下表[hash1]

return table[hash1] == null ? null : table[hash1].value;

编写此方法的更好方法是

// don't go around forever if the hash2 is poor.
for(int i = 0; i < TABLE_SIZE; i++) {
    Entry e = table[hash1];
    if (e == null) return null;
    if (e.key.equals(key)) return e.value;
    hash1 += hash2;
    hash1 %= TABLE_SIZE;
}
// should never happen if hash2 is well chosen.
return null;

最新更新