由于有一些混淆的算法Java的HashMap的是使用(在Sun /甲骨文/ OpenJDK的实现),这里的相关的源代码段(从OpenJDK的,1.6.0_20,在Ubuntu):
/**
* Returns the entry associated with the specified key in the
* HashMap. Returns null if the HashMap contains no mapping
* for the key.
*/
final Entry<K,V> getEntry(Object key) {
int hash = (key == null) ? 0 : hash(key.hashCode());
for (Entry<K,V> e = table[indexFor(hash, table.length)];
e != null;
e = e.next) {
Object k;
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
}
return null;
}
在查找表中的一个条目时,例如从get()
,containsKey()
和其他一些条目中调用此方法(引用来自第355行至第371行)。这里的for循环遍历入口对象形成的链表。
这里进入对象的代码(行691-705 + 759):
static class Entry<K,V> implements Map.Entry<K,V> {
final K key;
V value;
Entry<K,V> next;
final int hash;
/**
* Creates new entry.
*/
Entry(int h, K k, V v, Entry<K,V> n) {
value = v;
next = n;
key = k;
hash = h;
}
// (methods left away, they are straight-forward implementations of Map.Entry)
}
以后这个权利来了addEntry()
方法:
/**
* Adds a new entry with the specified key, value and hash code to
* the specified bucket. It is the responsibility of this
* method to resize the table if appropriate.
*
* Subclass overrides this to alter the behavior of put method.
*/
void addEntry(int hash, K key, V value, int bucketIndex) {
Entry<K,V> e = table[bucketIndex];
table[bucketIndex] = new Entry<K,V>(hash, key, value, e);
if (size++ >= threshold)
resize(2 * table.length);
}
这增加了在前面的新条目的条目,链接到旧的条目的第一个条目(如果没有这样的条目,则为null)。类似地,removeEntryForKey()
方法遍历列表并负责仅删除一个条目,让列表的其余部分保持不变。
因此,这里是每个存储桶的链接条目列表,我非常怀疑这从_20
更改为_22
,因为它从1.2开始就是这样。 (代码为(c)1997-2007 Sun Microsystems,并且可以在GPL下使用,但是可以更好地使用原始文件,该文件包含在Sun/Oracle的每个JDK的src.zip中,以及OpenJDK中)。
这是真的采取了由Sun /甲骨文在JDK 1.6.0_22两者`Hashtable`和`HashMap`。 – 2011-02-12 21:42:04
@Nikita:不确定Hashtable,我现在无法访问源代码,但我100%确定HashMap在我的调试器中看到过的每个版本中都使用链接而不是线性探测。 – 2011-02-12 21:45:34
@Michael那么,我现在正在查看HashMap的`public V get(Object key)'的源码(与上面的版本相同)。如果你确实在这些链表出现的地方找到了精确的版本,我很有兴趣知道。 – 2011-02-12 21:51:52