我看的JDK1.8的源码
public class LinkedHashMapDemo {
public static void main(String[]args){
Map m = new HashMap();
m.put(2, "b");
m.put(1, "a");
m.put(3, "c");
Set set = m.keySet();
Iterator keyit =set.iterator();
while(keyit.hasNext()){
int key = (Integer)keyit.next();
System.out.println(key + " : " + m.get(key));
}
System.out.println("====================");
Map m2 = new LinkedHashMap();
m2.put(2, "b");
m2.put(1, "a");
m2.put(3, "c");
Set set2 = m2.keySet();
Iterator keyit2 =set2.iterator();
while(keyit2.hasNext()){
int key = (Integer)keyit2.next();
System.out.println(key + " : " + m2.get(key));
}
}
}
运行后结果
1 : a
2 : b
3 : c
====================
2 : b
1 : a
3 : c
由结果可知LinkedHashMap 记录了key的插入顺序,那么LinkedHashMap是如何做到的呢?
public class LinkedHashMap
extends HashMap
implements Map{
transient LinkedHashMap.Entry head;
transient LinkedHashMap.Entry tail;
}
LinkedHashMap.Entry
static class Entry extends HashMap.Node {
Entry before, after;
Entry(int hash, K key, V value, Node next) {
super(hash, key, value, next);
}
}
LinkedHashMap 里多了head ,tail 。 head和tail都是LinkedHashMap.Entry,
LinkedHashMap.Entry继承HashMap.Node,只不过在它的基础上多了before,after的
引用,before就是前面插入的节点,after就是后面插入的节点。形成了双链表的结构。
因此可以想象出keyset的遍历肯定是从head开始
如果是我来写,我的代码是如下,返回的是list.
为什么jdkli的keyset返回的是set结构?该问题留待后面看了set的结构后再来分析。
//我的想象中的代码
public List keySet(){
LinkedHashMap.Entry entry;
if(head==null)
return null;
List list = ArrayList();
while((entry=head.after)!=null){
list.add(entry.getKey);
}
return list;
}
那jdk里的keyset如何实现的,继续
public Set keySet() {
Set ks = keySet;
if (ks == null) {
ks = new LinkedKeySet();
keySet = ks;
}
return ks;
}
final class LinkedKeySet extends AbstractSet {
。。。
public final Iterator iterator() {
return new LinkedKeyIterator();
}
。。。
}
final class LinkedKeyIterator extends LinkedHashIterator
implements Iterator {
//!!!nextNode()
public final K next() { return nextNode().getKey(); }
}
LinkedKeyIterator
继承了
LinkedHashIterator
,nextNode()
是LinkedHashIterator
里的一个方法,如下
abstract class LinkedHashIterator {
LinkedHashMap.Entry next;
LinkedHashMap.Entry current;
int expectedModCount;
LinkedHashIterator() {
//构造函数里将LinkedHashMap里的head赋值给next
next = head;
expectedModCount = modCount;
current = null;
}
public final boolean hasNext() {
return next != null;
}
final LinkedHashMap.Entry nextNode() {
LinkedHashMap.Entry e = next;
//在遍历的过程中不能做插入或删除linkedHashMap的操作,否则会报
ConcurrentModificationException
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
if (e == null)
throw new NoSuchElementException();
current = e;
//每次调用next()都将e.after赋给next
next = e.after;
return e;
}
nextNode()其实就是取(LinkedHashMap.Entry).after
LinkedHashMap extends HashMap,put的流程其实就是HashMap的put流程,
HashMap的put源码如下:
Node[] tab; Node p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
//!!! linkedhashmap重写newNode
tab[i] = newNode(hash, key, value, null);
else {
Node 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)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
//!!! linkedhashmap重写了newNode
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) {
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
//!!!afterNodeAccess
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
上面标记!!!的就是LinkedHashMap里的不同于HashMap的地方。分析如下
Node newNode(int hash, K key, V value, Node e) {
LinkedHashMap.Entry p =
new LinkedHashMap.Entry(hash, key, value, e);
//!!!维持了head,tail的关系
linkNodeLast(p);
return p;
}
private void linkNodeLast(LinkedHashMap.Entry p) {
LinkedHashMap.Entry last = tail;
//tail现在是p了
tail = p;
//第一次加,tail为空,则head,tail都指向p
if (last == null)
head = p;
else {
//p的上个插入为上个tail
p.before = last;
//上个tail 的下个为p
last.after = p;
}
}
这个方法里 accessOrder为true很关键,表示是否将范问过的节点放到最后。可以实现LRU
void afterNodeAccess(Node e) {
LinkedHashMap.Entry last;
//accessOrder为true否按是否将范问过的节点放到最后
if (accessOrder && (last = tail) != e) {
LinkedHashMap.Entry p =
(LinkedHashMap.Entry)e, b = p.before, a = p.after;
//访问过的节点放最后,最后的after肯定是null
p.after = null;
//如果访问的节点是头节点,则after节点就变成了头节点
if (b == null)
head = a;
else
//如果不是,则访问节点从链表移动到最后,它的after 指向了它的next
b.after = a;
//如果访问节点的after不是null after 的before 就指向了访问节点的before
if (a != null)
a.before = b;
else
//否则的话就是访问的末节点了
last = b;
//这里是防止了链表里只有一个节点的情况
if (last == null)
head = p;
else {
//不是的话就把访问节点的before指向last
p.before = last;
//last的after指向了访问节点
last.after = p;
}
//tail 就是访问的节点了
tail = p;
++modCount;
}
}
上面的算法就是囊括了链条中各个节点被访问后的情况,注释写的比较乱。
就是以下4种情况