001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.gui.util;
003
004import java.util.LinkedHashMap;
005import java.util.Map;
006import java.util.Objects;
007
008/**
009 * LRU cache (least recently used)
010 * @param <K> the type of keys maintained by this map
011 * @param <V> the type of mapped values
012 * @see <a href="http://java-planet.blogspot.com/2005/08/how-to-set-up-simple-lru-cache-using.html">
013 *     Java Planet: How to set up a simple LRU cache using LinkedHashMap</a>
014 */
015public final class LruCache<K, V> extends LinkedHashMap<K, V> {
016    private static final long serialVersionUID = 1L;
017    private final int capacity;
018
019    /**
020     * Constructs an empty {@code LruCache} instance with the given capacity
021     * @param capacity the capacity
022     */
023    public LruCache(int capacity) {
024        super(capacity + 1, 1.1f, true);
025        this.capacity = capacity;
026    }
027
028    @Override
029    protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
030        return size() > capacity;
031    }
032
033    @Override
034    public boolean equals(Object o) {
035        if (this == o) return true;
036        if (o == null || getClass() != o.getClass()) return false;
037        if (!super.equals(o)) return false;
038        LruCache<?, ?> lruCache = (LruCache<?, ?>) o;
039        return capacity == lruCache.capacity;
040    }
041
042    @Override
043    public int hashCode() {
044        return Objects.hash(super.hashCode(), capacity);
045    }
046}