【发布时间】:2018-02-01 15:17:43
【问题描述】:
在这里,我正在尝试实现链式哈希表。在这里,当我输入相同的键时,它会与现有键连接并为值加一。我得到的问题是,当我打印最终表格时,它给出了错误的值。每次都有一个键,而其他相同的键正在连接在一起。
插入函数编码如下。
public void insert (String key, int value){
int hashValue= generateHashValue(key); //find what bucket suits for each key
if(table[hashValue] == null) {
table[hashValue] = new HashTableLinked(key, value);//enter new key
}
else{
HashTableLinked entry = table[hashValue];
boolean condition =false;
while (entry.next!= null){
if (entry.getKey().equals(key)) {
entry.setValue(entry.getValue()+1); //trying to add +1 for existing key
condition = true;
break;
}
entry = entry.next;
}
if(!condition) {
entry.next = new HashTableLinked(key, value);
}
}
}
如果需要,hashTableLinked 类如下,
public class HashTableLinked {
private String key;
int value;
HashTableLinked next;
public HashTableLinked(String key,int value){
this.key = key;
this.value = value;
this.next = null;
public void setValue(int value) {
this.value = value;
}
public String getKey() {
return key;
}
public int getValue(){
return value;
}
}
当我输入包含 5 个“the”s 的输入行时
We the People the the the of freedom in Order to form the
输出是
Bucket 9 : the 4
the 1
【问题讨论】:
-
你调试过你的代码吗?有什么理由实现自己的哈希表而不是使用 Java 的?
-
这是作业吗?
-
对不起,如果没有足够的代码可以运行,很难猜出问题出在哪里,例如方法 generateHashValue(key) 在这里没有描述。 {table} 属性也是如此。
-
我认为代码的另一部分是不必要的..因为它包含更多行..@Kamil...
-
这是一种家庭作业..但它不是你认为的家庭作业:) @JPRLCol