LinkedHashMap学习
关系图
双向链表
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;
}
其他重要方法
-
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());
}
}
}
评论区