public boolean isCollide(String key, String value){
int index = key.hashCode();
if (this.key_array[index]==null) return false;
else return true;
}
public void addValue(String key, String value){
Hashtable hashtable = new Hashtable(key,value);
int index = key.hashCode();
if (isCollide(key,value)) {
hashtable.key_array[index]=key;
hashtable.value_array[index]=value;
}
else{
LinkedList<String> linkedList = new LinkedList<>();
linkedList.add(value); //how to create a linkedlist on a hashtable?
}
}
我正在从头开始实现 Hashtable。我想知道如何在哈希表中创建链接列表?上面的代码几乎是错误的,但我希望它能说明我的想法。因此,如果发生冲突,那么我想从该冲突索引开始创建一个链表。有人可以给我一些指导吗?谢谢!
最佳答案
以下是 Java HashMap 内部的实现方式:
class Entry<K,V> implements Map.Entry<K,V> {
final K key;
V value;
Entry<K,V> next;
int hash;
/**
* Creates new entry.
*/
Entry(int h, K k, V v, Entry<K,V> n) {
value = v;
next = n;
key = k;
hash = h;
}
// rest of methods here...
}
入口类维护内部“next”属性,用于构建冲突键的链接列表。
基本上,键和值对在内部存储为 Entry 类的实例。如果发生冲突,新的 Entry 实例将作为下一个节点添加到槽中的最后一个项目。伪代码:
table[i].next = newEntry;
<小时/>
关于java - 如何在具有特定索引的哈希表中创建链表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30157015/