如何在具有特定索引的 hash-table 中创建链表?
how to create a linked-list in a hash-table with the specific index?
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...
}
条目 class 维护内部 "next" 属性 以构建冲突键的链表。
基本上键和值对作为条目的实例在内部存储class。如果发生冲突,新的 Entry 实例将作为下一个节点添加到插槽中的最后一个项目。伪代码:
table[i].next = newEntry;
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...
}
条目 class 维护内部 "next" 属性 以构建冲突键的链表。
基本上键和值对作为条目的实例在内部存储class。如果发生冲突,新的 Entry 实例将作为下一个节点添加到插槽中的最后一个项目。伪代码:
table[i].next = newEntry;