侧边栏壁纸
博主头像
晓果冻博主等级

行动起来,活在当下

  • 累计撰写 135 篇文章
  • 累计创建 16 个标签
  • 累计收到 91 条评论

目 录CONTENT

文章目录

LinkedHashMap学习

Administrator
2022-04-12 / 0 评论 / 2 点赞 / 401 阅读 / 3092 字

LinkedHashMap学习

关系图

image-20220412081759428

双向链表
    static class Entry<K,V> extends HashMap.Node<K,V> {
    //after、before 双向链表
        Entry<K,V> before, after;
        Entry(int hash, K key, V value, Node<K,V> next) {
            super(hash, key, value, next);
        }
    }
构造方法
public LinkedHashMap(int initialCapacity, float loadFactor) {
	super(initialCapacity, loadFactor);
	accessOrder = false;
} 
    
public LinkedHashMap(int initialCapacity) {
    super(initialCapacity);
    accessOrder = false;
}   
    
public LinkedHashMap() {
    super();
    accessOrder = false;
}

public LinkedHashMap(Map<? extends K, ? extends V> m) {
   super();
   accessOrder = false;
   putMapEntries(m, false);
}

/*
*一般用此构造方法,accessOrder用来指定是否按顺序访问,如果为true就是按顺序访问,false根据新增排序
*/
public LinkedHashMap(int initialCapacity,
                         float loadFactor,
                         boolean accessOrder) {
    super(initialCapacity, loadFactor);
    this.accessOrder = accessOrder;
}

image-20220412082846866

image-20220412082917933

其他重要方法
  • get方法

    public V get(Object key) {
            Node<K,V> e;
            if ((e = getNode(hash(key), key)) == null)
                return null;
            //accessOrder为ture的话,则将元素移动到末尾
            if (accessOrder)
                afterNodeAccess(e);
            return e.value;
    }
    
  • clear方法

    public void clear() {
       super.clear();
       //头尾都指向空
       head = tail = null;
    }
    
实现LRU
package com.example.test.Lru;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author 晓果冻
 * @version 1.0
 * @date 2022/4/12 8:36
 */
public class LruCache<K,V> extends LinkedHashMap<K,V> {
    /**
     * 容量
     */
    private int capacity;

    public LruCache(int capacity) {
        super(capacity,0.75f,true);
        this.capacity = capacity;
    }

    /**
     * 清理头结点
     * @param eldest
     * @return
     */
    @Override
    protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
        return size()>capacity;
    }

    public static void main(String[] args) {
        LruCache<Integer,Integer> map = new LruCache(3);
        map.put(1,1);
        map.put(2,2);
        map.put(3,3);
        //容量达到3,删除最前面的
        map.put(4,4);
        for (Map.Entry<Integer,Integer> entry:map.entrySet()){
            System.out.println("key:"+entry.getKey()+",value:"+entry.getValue());
        }
    }
}

image-20220412084347684

2

评论区