Collection集合-LinkedHashMap

继承类和实现接口

可以看出LinkedHashMap继承了HashMap,那么主要方法都是和HashMap相同,那么主要看相对于HashMap重写了那些方法就能确定LinkedHashMap相对于HashMap的特征

public class LinkedHashMap<K,V>
    extends HashMap<K,V>
    implements Map<K,V>
{

存储数据的Entry类进行重写

新增:新增两个参数before,after 记录当前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);
        }
    }

增加了记录首位的两个实体类

新增了记录链式结构中起点和结尾的两个实体类可以通过这两个节点获取顺序节点

  transient LinkedHashMap.Entry<K,V> head;

   /**
   * The tail (youngest) of the doubly linked list.
   */
  transient LinkedHashMap.Entry<K,V> tail;

新建节点的方法重写

这里是相对于HashMap最大的不同

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

  private void linkNodeLast(LinkedHashMap.Entry<K,V> p) {
        LinkedHashMap.Entry<K,V> last = tail;
        tail = p;
        //最后一个tail节点为空,插入值就为head节点
        if (last == null)
            head = p;
        else {
            //节点链式存储前后节点地址
            p.before = last;
            last.after = p;
        }
    }

总结

    1. LinkedHashMap继承HashMap,所以主要方法和HashMap是相通的
    1. LinkedHashMap重写了存储数据的Entry节点结构,增加了记录当前节点的前后节点位置
    1. LinkedHashMap新增了head和tail两个节点,在存储数据创建节点的时候存储首位节点位置
    1. LinkedHashMap内部顺序结构是通过双向链表关联起来的
posted @ 2023-08-22 15:02  PerfectLi  阅读(24)  评论(0)    收藏  举报