内部结构图

Java数据结构-LinkedHashmap_数组

实现原理

其实如果不看图中的横向引用而只看纵向向引用的话,LinkedHashMap和HashMap是差不多的

HashMap.Node.next相当于LinkedHashMap.Entry.after.

LinkedHashMap内部维护的Entry比HashMap中维护的Node多了一个before属性,

HashMap.Node:

static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;
//此处省略一万行代码
}

LinkedHashMap.Entry

static class Entry<K,V> extends HashMap.Node<K,V> {
Entry<K,V> before, after;
Entry(int hash, K key, V value, Node<K,V> next) {
super(hash, key, value, next);
}
}

​Entry<K,V> before, after;​​分别代表前一个引用和后一个引用。也就是说,LinkedHashMap中的entry每一个对象都持有他前后对象的引用。所以顺序是和插入的时候保持一致的。

特点

有序,顺序和插入时保持一致。

迭代的所需时间与数组本身大小无关,只与实际元素数量有关

常用方法源码

put(K key, V value)

public V put(K key, V value) {
if (table == EMPTY_TABLE) {
inflateTable(threshold);//如果是第一次吊用put方法则初始化数组,默认大小16
}
if (key == null)
return putForNullKey(value);
int hash = hash(key);
int i = indexFor(hash, table.length);//通过key决定key在hashmap中存放的位置
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
Object k;
//如果key相同则替换原有的value
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}

modCount++;
addEntry(hash, key, value, i);//添加元素方法
return null;
}

void addEntry(int hash, K key, V value, int bucketIndex) {
if ((size >= threshold) && (null != table[bucketIndex])) {
resize(2 * table.length);//进行数组扩容,扩容大小为原大小2倍
hash = (null != key) ? hash(key) : 0;
bucketIndex = indexFor(hash, table.length);
}
createEntry(hash, key, value, bucketIndex);//创建entry对象并放入数组中
}

void createEntry(int hash, K key, V value, int bucketIndex) {
HashMap.Entry<K,V> old = table[bucketIndex];
Entry<K,V> e = new Entry<>(hash, key, value, old);
table[bucketIndex] = e;
e.addBefore(header);//修改引用
size++;
}

private void addBefore(Entry<K,V> existingEntry) {
after = existingEntry;
before = existingEntry.before;
before.after = this;
after.before = this;
}

get(Object key)

public V get(Object key) {
Entry<K,V> e = (Entry<K,V>)getEntry(key);
if (e == null)
return null;
e.recordAccess(this);
return e.value;
}
final Entry<K,V> getEntry(Object key) {
if (size == 0) {
return null;
}

int hash = (key == null) ? 0 : hash(key);
for (Entry<K,V> e = table[indexFor(hash, table.length)];
e != null;
e = e.next) {
Object k;
//比较hash并获取值返回
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
}
return null;
}