LinkedHashMap的Node之间通过双向链表连接 LinkedHashMap可以按照插入顺序或访问顺序进行遍历 LinkedHashMap的访问顺序比HashMap高效,遍历双向链表就行,而HashMap需要bucket 但LinkedHashMap的插入性能会低于HashMap,因为需要维护双向链表 new LinkedHashMap(capacity, 0.75f, true); 指定第三个参数为true,则进行访问顺序遍历 get一个key时,会把这个key对应的Node移动到链表末尾 所以也可以用LinkedHashMap实现LRU缓存,队首的Node就是最久未访问的Node public class LRUCache<K, V> extends LinkedHashMap<K,V> { int capacity; public LRUCache(int capacity) { super(capacity, 0.75f, true); this.capacity = capacity; } @Override protected boolean removeEldestEntry(Map.Entry<K, V> eldest) { return size() > capacity; } }
LinkedHashMap
于 2023-12-09 21:41:38 首次发布