我们设计的代码如下所示:
package com.rgf.jihe;
import java.util.HashMap;
import java.util.LinkedHashMap;
/**
* LinkedHashMap的底层实现原理(了解)
* 源码如下所示:
* public class LinkedHashMap<K,V>
* extends HashMap<K,V>
* implements Map<K,V>
* 父类为HashMap.我们进行继承父类
* public LinkedHashMap() {
* super();
* accessOrder = false;
* }
* 调用的是父类的put方法。
* public V put(K key, V value) {
* return putVal(hash(key), key, value, false, true);
* }
* 同时putVal也是调用的是HashMap的方法,
* final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
* boolean evict) {
* Node<K,V>[] tab; Node<K,V> p; int n, i;
* if ((tab = table) == null || (n = tab.length) == 0)
* n = (tab = resize()).length;
* if ((p = tab[i = (n - 1) & hash]) == null)
* tab[i] = newNode(hash, key, value, null);
* else {
* Node<K,V> e; K k;
* if (p.hash == hash &&
* ((k = p.key) == key || (key != null && key.equals(k))))
* e = p;
* else if (p instanceof TreeNode)
* e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
* else {
* for (int binCount = 0; ; ++binCount) {
* if ((e = p.next) == null) {
* p.next = newNode(hash, key, value, null);
* if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
* treeifyBin(tab, hash);
* break;
* }
* if (e.hash == hash &&
* ((k = e.key) == key || (key != null && key.equals(k))))
* break;
* p = e;
* }
* }
* if (e != null) { // existing mapping for key
* V oldValue = e.value;
* if (!onlyIfAbsent || oldValue == null)
* e.value = value;
* afterNodeAccess(e);
* return oldValue;
* }
* }
* ++modCount;
* if (++size > threshold)
* resize();
* afterNodeInsertion(evict);
* return null;
* }
* 里面的newNode为LinkedHashMap,重写了该方法:
* Node<K,V> newNode(int hash, K key, V value, Node<K,V> e) {
* LinkedHashMap.Entry<K,V> p =
* new LinkedHashMap.Entry<K,V>(hash, key, value, e);
* linkNodeLast(p);
* return p;
* }
* Entry的底层如下所示: (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);
* }
* }
* 而Node的底层如下所示;(HashMap中的内部类:Node)
* static class Node<K,V> implements Map.Entry<K,V> {
* final int hash;
* final K key;
* V value;
* Node<K,V> next;
*
* Node(int hash, K key, V value, Node<K,V> next) {
* this.hash = hash;
* this.key = key;
* this.value = value;
* this.next = next;
* }
*HashSet的底层是HashMap,所存储的值相当于key-value里面的key.
*
*/
public class LinkedHashMapTest {
public static void main(String[] args) {
HashMap map = new HashMap();
map.put(123,"AA");
map.put(345,"BB");
map.put(12,"CC");
System.out.println(map);
LinkedHashMap l = new LinkedHashMap();
l.put(123,"AA");
l.put(345,"BB");
l.put(12,"CC");
System.out.println(l);
}
}
运行之后如下所示: