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;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句