当前位置: 移动技术网 > IT编程>开发语言>Java > Java中LinkedHashMap源码解析

Java中LinkedHashMap源码解析

2019年07月19日  | 移动技术网IT编程  | 我要评论

概述:

linkedhashmap实现map继承hashmap,基于map的哈希表和链该列表实现,具有可预知的迭代顺序。

linedhashmap维护着一个运行于所有条目的双重链表结构,该链表定义了迭代顺序,可以是插入或者访问顺序。

 linthashmap的节点对象继承hashmap的节点对象,并增加了前后指针 before after:

/**
 * linkedhashmap节点对象
 */
 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);
  }
 }

linthashmap初始化:

accessorder,简单说就是这个用来控制元素的顺序,
accessorder为true: 表示按照访问的顺序来,也就是谁最先访问,就排在第一位
accessorder为false表示按照存放顺序来,就是你put元素的时候的顺序。

public linkedhashmap(int initialcapacity, float loadfactor) {
  super(initialcapacity, loadfactor);
  accessorder = false;
 }

 /**
  * 生成一个空的linkedhashmap,并指定其容量大小,负载因子使用默认的0.75,
  * accessorder为false表示按照存放顺序来,就是你put元素的时候的顺序
  * accessorder为true: 表示按照访问的顺序来,也就是谁最先访问,就排在第一位
  */
 public linkedhashmap(int initialcapacity) {
  super(initialcapacity);
  accessorder = false;
 }
 /**
  * 生成一个空的hashmap,容量大小使用默认值16,负载因子使用默认值0.75
  * 默认将accessorder设为false,按插入顺序排序.
  */
 public linkedhashmap() {
  super();
  accessorder = false;
 }
 /**
  * 根据指定的map生成一个新的hashmap,负载因子使用默认值,初始容量大小为math.max((int) (m.size() / default_load_factor) + 1,default_initial_capacity)
  * 默认将accessorder设为false,按插入顺序排序.
  */
 public linkedhashmap(map<? extends k, ? extends v> m) {
  super();
  accessorder = false;
  putmapentries(m, false);
 }
 /**
  * 生成一个空的linkedhashmap,并指定其容量大小和负载因子,
  * 默认将accessorder设为true,按访问顺序排序
  */
 public linkedhashmap(int initialcapacity,
       float loadfactor,
       boolean accessorder) {
  super(initialcapacity, loadfactor);
  this.accessorder = accessorder;
 }

putmapentries(m,false)调用父类hashmap的方法,继而根据hashmap的put来实现数据的插入:

 /**
  * implements map.putall and map constructor
  *
  * @param m the map
  * @param evict false when initially constructing this map, else
  * true (relayed to method afternodeinsertion).
  */
 final void putmapentries(map<? extends k, ? extends v> m, boolean evict) {
  int s = m.size();
  if (s > 0) {
   if (table == null) { // pre-size
    float ft = ((float)s / loadfactor) + 1.0f;
    int t = ((ft < (float)maximum_capacity) ?
       (int)ft : maximum_capacity);
    if (t > threshold)
     threshold = tablesizefor(t);
   }
   else if (s > threshold)
    resize();
   for (map.entry<? extends k, ? extends v> e : m.entryset()) {
    k key = e.getkey();
    v value = e.getvalue();
    putval(hash(key), key, value, false, evict);
   }
  }
 }

存储:

put调用的hashmap的put方法,调用两个空方法,由linkedhashmap实现

public v put(k key, v value) {
  return putval(hash(key), key, value, false, true);
 }
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;
 }

在hashmap中红色部分为空实现:

 void afternodeaccess(node<k,v> p) { }
 void afternodeinsertion(boolean evict) { }

然后看下linkedhashmap怎么实现这两方法:

将当前节点e移动到双向链表的尾部。每次linkedhashmap中有元素被访问时,就会按照访问先后来排序,先访问的在双向链表中靠前,越后访问的越接近尾部。当然只有当accessorder为true时,才会执行这个操作。

void afternodeaccess(node<k,v> e) {
  linkedhashmap.entry<k,v> last;
  // 若访问顺序为true,且访问的对象不是尾结点
  if (accessorder && (last = tail) != e) {
   // 向下转型,记录p的前后结点
   linkedhashmap.entry<k,v> p =
    (linkedhashmap.entry<k,v>)e, b = p.before, a = p.after;
   // p的后结点为空
   p.after = null;
   // 如果p的前结点为空
   if (b == null)
    // a为头结点
    head = a;
   else // p的前结点不为空
    // b的后结点为a
    b.after = a;
   // p的后结点不为空
   if (a != null)
    // a的前结点为b
    a.before = b;
   else // p的后结点为空
    // 后结点为最后一个结点
    last = b;
   // 若最后一个结点为空
   if (last == null)
    // 头结点为p
    head = p;
   else { // p链入最后一个结点后面
    p.before = last;
    last.after = p;
   }
   // 尾结点为p
   tail = p;
   // 增加结构性修改数量
   ++modcount;
  }
 }

afternodeinsertion方法 evict为true时删除双向链表的头节点

 void afternodeinsertion(boolean evict) { // possibly remove eldest
  linkedhashmap.entry<k,v> first;
     //头结点不为空,删除头结点
  if (evict && (first = head) != null && removeeldestentry(first)) {
   k key = first.key;
   removenode(hash(key), key, null, false, true);
  }
 }

删除操作调用hashmap的remove方法实现元素删除,remove调用removenode,而removenode有一个方法需要linkedhashmap来实现:

将e节点从双向链表中删除,更改e前后节点引用关系,使之重新连成完整的双向链表。

 void afternoderemoval(node<k,v> e) { // unlink
  linkedhashmap.entry<k,v> p =
   (linkedhashmap.entry<k,v>)e, b = p.before, a = p.after;
  p.before = p.after = null;
  if (b == null)
   head = a;
  else
   b.after = a;
  if (a == null)
   tail = b;
  else
   a.before = b;
 }

读取:

e不为空,则获取e的value值并返回。

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;
 }

accessorder为true,也就是说按照访问顺序获取内容。

 void afternodeaccess(node<k,v> e) {
  linkedhashmap.entry<k,v> last;
  // 若访问顺序为true,且访问的对象不是尾结点
  if (accessorder && (last = tail) != e) {
   // 向下转型,记录p的前后结点
   linkedhashmap.entry<k,v> p =
    (linkedhashmap.entry<k,v>)e, b = p.before, a = p.after;
   // p的后结点为空
   p.after = null;
   // 如果p的前结点为空
   if (b == null)
    // a为头结点
    head = a;
   else // p的前结点不为空
    // b的后结点为a
    b.after = a;
   // p的后结点不为空
   if (a != null)
    // a的前结点为b
    a.before = b;
   else // p的后结点为空
    // 后结点为最后一个结点
    last = b;
   // 若最后一个结点为空
   if (last == null)
    // 头结点为p
    head = p;
   else { // p链入最后一个结点后面
    p.before = last;
    last.after = p;
   }
   // 尾结点为p
   tail = p;
   // 增加结构性修改数量
   ++modcount;
  }
 }

linkedhashmap的几个迭代器:

抽象类linkedhashiterator 实现具体删除,判断是否存在下个结点,迭代的逻辑。

linkedkeyiterator 继承自linkedhashiterator,实现了iterator接口,对linkedhashmap中的key进行迭代。
linkedvalueiterator 继承自linkedhashiterator,实现了iterator接口,对linkedhashmap中的value进行迭代
linkedentryiterator 继承自linkedhashiterator,实现了iterator接口,对linkedhashmap中的结点进行迭代

abstract class linkedhashiterator {
  //下一个节点
  linkedhashmap.entry<k,v> next;
  //当前节点
  linkedhashmap.entry<k,v> current;
  //期望的修改次数
  int expectedmodcount;

  linkedhashiterator() {
   //next赋值为头结点
   next = head;
   //赋值修改次数
   expectedmodcount = modcount;
   //当前节点赋值为空
   current = null;
  }
  //是否存在下一个结点
  public final boolean hasnext() {
   return next != null;
  }

  final linkedhashmap.entry<k,v> nextnode() {
   linkedhashmap.entry<k,v> e = next;
   //检查是否存在结构性改变
   if (modcount != expectedmodcount)
    throw new concurrentmodificationexception();
   //结点为null nosuchelementexception
   if (e == null)
    throw new nosuchelementexception();
   //不为null,赋值当前节点
   current = e;
   //赋值下一个结点
   next = e.after;
   return e;
  }
  //删除操作
  public final void remove() {
   node<k,v> p = current;
   if (p == null)
    throw new illegalstateexception();
   if (modcount != expectedmodcount)
    throw new concurrentmodificationexception();
   current = null;
   k key = p.key;
   //移除结点操作
   removenode(hash(key), key, null, false, false);
   expectedmodcount = modcount;
  }
 }

 final class linkedkeyiterator extends linkedhashiterator
  implements iterator<k> {
  public final k next() { return nextnode().getkey(); }
 }

 final class linkedvalueiterator extends linkedhashiterator
  implements iterator<v> {
  public final v next() { return nextnode().value; }
 }

 final class linkedentryiterator extends linkedhashiterator
  implements iterator<map.entry<k,v>> {
  public final map.entry<k,v> next() { return nextnode(); }
 }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网