【问题标题】:Error with get method of double hashing hash table双散列表的get方法出错
【发布时间】:2013-11-29 15:49:57
【问题描述】:

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

 /* 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;

谁能帮帮我?

【问题讨论】:

  • 它说什么?空指针异常?这意味着 table[hash1] 为空。如果它是 IndexOutOfBounds 则意味着 hash1 计算错误。我们需要更多信息在这里
  • @EdgarBoda 编译器没有告诉我,它只是说“在 HashTable.get(HashTable.java:73)”
  • @EdgarBoda 我用 java 博士再次尝试,它说 nullpointerexception
  • 好的,我想说你的问题是table[hash1] 为空。当您在 while 循环的头部访问 table[hash1] 时,索引应该没问题。所以你应该检查为什么table[hash1] 为空。
  • 请发布您的程序的sscce

标签: java hash double-hashing


【解决方案1】:

退出循环的条件之一是

while (table[hash1] != null

这意味着你知道 table[hash1] 可能是 null 但你知道

return table[hash1].value;

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

我建议你在尝试使用它之前检查 table[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;

【讨论】:

    猜你喜欢
    • 2011-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-20
    • 2016-07-15
    • 2012-10-19
    • 1970-01-01
    相关资源
    最近更新 更多