LinkedHashMap源码浅析(二)

2014-11-24 02:03:54 · 作者: · 浏览: 1

void addEntry(int hash, K key, V value, int bucketIndex)

{

createEntry(hash, key, value, bucketIndex);

// Remove eldest entry if instructed, else grow capacity if appropriate

Entry eldest = header.after;

if (removeEldestEntry(eldest))

{

removeEntryForKey(eldest.key);

}

else

{

if (size >= threshold)

resize(2 * table.length);

}

}

/**

* This override differs from addEntry in that it doesn't resize the

* table or remove the eldest entry.

*/

void createEntry(int hash, K key, V value, int bucketIndex)

{

HashMap.Entry old = table[bucketIndex];

Entry e = new Entry(hash, key, value, old);

table[bucketIndex] = e;

e.addBefore(header);

size++;

}

/**

* Inserts this entry before the specified existing entry in the list.

*/

private void addBefore(Entry existingEntry)

{

after = existingEntry;

before = existingEntry.before;

before.after = this;

after.before = this;

}

addEntry方法是父类HashMap的一个方法,被put相关的方法所调用即在新增元素的时候调用。

我们通过形象的图来看一个基本的流程:

(从初始化到添加了3个元素过程中,各个元素before、after引用变化,画的有点丑,呵呵,不过意思能够表达清楚,代码的内容就不再累述了,大体和HashMap类似!)

再介绍一个get方法

Java代码

/**

* Returns the value to which the specified key is mapped,

* o