LinkedHashMap 学习了解

一、概念

定义:
public class LinkedHashMap<K,V> extends HashMap<K,V>
implements Map<K,V>

LinkedHashMap 继承 HashMap 的功能,增加了元素的有效性


    /**
     * The head (eldest) of the doubly linked list.
     * 双向列表,表头
     */
    transient LinkedHashMap.Entry<K,V> head;

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

    /**
     * The iteration ordering method for this linked hash map: <tt>true</tt>
     * for access-order, <tt>false</tt> for insertion-order.
     * 从构造方法中看出,默认为 false 插入顺序决定了元素的有序
     * 可以自定义为 true,表示 访问顺序,最近访问的元素放置列表尾部
     * @serial
     */
    final boolean accessOrder;
	public LinkedHashMap() {
        super();
        accessOrder = false;
    }

在这里插入图片描述

特点:
1、HashMap+双向链表 的特点,增删改查效率高
2、插入元素有序
3、key 和 value 都可以为 null (HashMap 可以)
4、除了继承 HashMap 的结构,还对所有 Entry 节点维护了双向链表。当put元素时,不但要把它加入到HashMap中去,还要加入到双向链表中

二、举例演示

 public static void test3() {

        log.info("1、默认按照插入顺序排序");
        LinkedHashMap<Student, Integer> studentInfoMap = new LinkedHashMap<>();
        studentInfoMap.put(new Student("小王", 9), 88);
        studentInfoMap.put(new Student("小张", 10), 80);
        studentInfoMap.put(new Student("小李", 11), 90);
        studentInfoMap.put(new Student("小赵", 8), 100);

        studentInfoMap.forEach((key,value) ->{
            log.info("key:{},value:{}",key,value);
        });

        log.info("2、按照访问顺序排序");
        LinkedHashMap<Student, Integer> studentInfoMap1 = new LinkedHashMap<>(16,0.75f,true);
        Student student1 = new Student("小王", 9);
        studentInfoMap1.put(student1,88);
        studentInfoMap1.put(new Student("小张", 10), 80);
        studentInfoMap1.put(new Student("小李", 11), 90);
        studentInfoMap1.put(new Student("小赵", 8), 100);
        log.info("这里访问 key 为 student1的元素 小王");
        studentInfoMap1.get(student1);
        studentInfoMap1.forEach((key,value) ->{
            log.info("key:{},value:{}",key,value);
        });
    }

输出:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值