LruCache

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

public class LruCache2 extends LinkedHashMap{

  private int cap;

  public LruCache2(int cap){
    super(16, 0.75f,true);
    this.cap = cap;
  }

  @Override
  public boolean removeEldestEntry(Map.Entry eldestEntry){
    return  size() > cap;
  }

  public static void main(String[] args) {
    LruCache2 cache = new LruCache2(2);
    cache.put(1,1);
    cache.put(2,2);
    cache.put(3,3);
    cache.put(4,4);
    cache.put(5,5);
    cache.put(6,6);
    System.out.println(cache.get(1));
    System.out.println(cache.get(2));
    System.out.println(cache.get(3));
    System.out.println(cache.get(4));
    System.out.println(cache.get(5));
    System.out.println(cache.get(6));
    System.out.println(cache.size());
  }
}

null
null
null
null
5
6
2

import java.util.HashMap;
import java.util.Map;

public class LruCache<K, V> {

  public Map<K, Node> getMap() {
    return map;
  }

  private Map<K, Node> map;
  private Node<K, V> head;
  private Node<K, V> tail;
  private int cacheSize;

  public LruCache(int cacheSize) {
    if (cacheSize < 1) throw new IllegalArgumentException();
    this.cacheSize = cacheSize;
    map = new HashMap<>();
  }


    static class Node<K, V> {
     K key;
     V value;
     Node<K, V> prev;
     Node<K, V> next;

    Node( K key, V value, Node<K, V> prev, Node<K, V> next) {
      this.key = key;
      this.value = value;
      this.prev = prev;
      this.next = next;
    }

      @Override
      public String toString() {
        return "Node{" +
            "key=" + key.toString() +
            ", value=" + value.toString() +
            '}';
      }
    }

  public V get(K key) {
    Node<K, V> e, last, before, after;
    e = map.get(key);
    if (e == null) {
      return null;
    }
    if ((last = tail) != e) {
      before = e.prev;
      after = e.next;
      if (before != null) {
        before.next =after;
      }
      if (after != null) {
        after.prev = before;
      }
      last.next = e;
      tail =e;
    }
    return e.value;
  }


  public void put(K key, V value) {
    Node<K, V> e, last, first, second;
    if ((last = tail) != null) {
      e = new Node<>(key ,value, last, null);
      last.next = e;
      tail = e;
    } else {
      head = tail = e = new Node<K, V>(key, value, null, null);
    }
    map.put(key, e);
    if ( map.size() > cacheSize && (first = head) != null && (second = first.next) != null) {
      second.prev = null;
      head = second;
      map.remove(first.key);
    }
  }

  public static void main(String[] args) {
    LruCache cache = new LruCache(1);
    cache.put(1, 1);
    cache.put(2, 2);
    System.out.println(cache.get(1));
    System.out.println(cache.get(2));
    System.out.println(cache.get(3));
    System.out.println(cache.getMap());
  }
}

null
2
null
{2=Node{key=2, value=2}}

原文地址:https://www.cnblogs.com/tonggc1668/p/11925214.html