jdk8源码7---集合6---LinkedHashMap
一、签名
public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V> |
实现了Map接口,继承了HashMap。
二、成员变量
transient LinkedHashMap.Entry<K,V> head; 双向链表的头 |
transient LinkedHashMap.Entry<K,V> tail; // 双向链表的尾 |
final boolean accessOrder; //控制读取的顺序,true表示访问的顺序,false表示插入的顺序 默认为false。 |
|
三、构造方法
public HashSet() { map = new HashMap<>(); } |
transient LinkedHashMap.Entry<K,V> head; |
transient LinkedHashMap.Entry<K,V> tail; |
final boolean accessOrder; |
HashSet(int initialCapacity, float loadFactor, boolean dummy) { map = new LinkedHashMap<>(initialCapacity, loadFactor); } // 注意了 这里是LinkedHashMap。 |
四、成员方法
public V get(Object key) { Node<K,V> e; if ((e = getNode(hash(key), key)) == null) return null; if (accessOrder) afterNodeAccess(e); return e.value; } |
final Node<K,V> getNode(int hash, Object key) { Node<K,V>[] tab; Node<K,V> first, e; int n; K k; if ((tab = table) != null && (n = tab.length) > 0 && (first = tab[(n - 1) & hash]) != null) { if (first.hash == hash && // always check first node ((k = first.key) == key || (key != null && key.equals(k)))) return first; if ((e = first.next) != null) { if (first instanceof TreeNode) return ((TreeNode<K,V>)first).getTreeNode(hash, key); do { if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) return e; } while ((e = e.next) != null); } } return null; } |
void afterNodeAccess(Node<K,V> e) { // move node to last LinkedHashMap.Entry<K,V> last; if (accessOrder && (last = tail) != e) { LinkedHashMap.Entry<K,V> p = (LinkedHashMap.Entry<K,V>)e, b = p.before, a = p.after; p.after = null; if (b == null) head = a; else b.after = a; if (a != null) a.before = b; else last = b; if (last == null) head = p; else { p.before = last; last.after = p; } tail = p; ++modCount; } }
|
put方法和HashMap的方法一致。
public boolean containsValue(Object value) { for (LinkedHashMap.Entry<K,V> e = head; e != null; e = e.after) { V v = e.value; if (v == value || (value != null && value.equals(v))) return true; } return false; } |
contiainsValue方法,就是遍历整个linkedHashMap,将每个Entry的value都比较一下。
五、遍历方式 略
六、总结
1.accessOrder的作用。
False的情况下(默认),按照插入时候的顺序来访问每个元素。
True的情况,每次调用get(Kk)的时候,都会对HashTable发生改变。它会按照访问顺序来改变HashTable结构。
最后
如果你觉得写的还不错,就关注下公众号呗,关注后,有点小礼物回赠给你。
你可以获得5000+电子书,java,springCloud,adroid,python等各种视频教程,IT类经典书籍,各种软件的安装及破解教程。
希望一块学习,一块进步!