The principle LinkedHashMap

LinkedHashMap properties

HashMap stored are unordered, when put in a certain order when the stored hash value sequence HashMap is key, and when the iterator traversal is disordered, and sometimes we need a map to insertion order returned, so should be shipped LinkedHashMap born.

The principle

LinkedHashMap achieve HashMap based just outside table, extra maintains a doubly linked list. Implement methods newNode, afterNodeRemoval the like, PUT and remove when increased or decreased to maintain its internal list subclasses implement Iterator interface, internal logic returns linked list data as in FIG.

LruCache与LinkedHashMap

LinkedHashMap characteristics achieved by using very simple lru queue, when the queue buffer is full, the head will be limited eliminated node, each node will get request is placed to the end of the queue, then the head node data is not frequently used, and a method using removeEldestEntry, judgment and put out of the data in time. Code is as follows public class MyLruCache <K, V> {private static final float hashTableLoadFactor = 0.75f; private LinkedHashMap <K, V> map; private int cacheSize;

public MyLruCache(int cacheSize) {
    this.cacheSize = cacheSize;
    int hashTableCapacity= (int) (Math.ceil(cacheSize/hashTableLoadFactor)+1);
    map=new LinkedHashMap<K,V>(hashTableCapacity,hashTableLoadFactor,true){
      
        @Override
        protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
            return size() > MyLruCache.this.cacheSize;
        }
    };
}

public V get(K key){
    return map.get(key);
}
public void put(K key,V value){
    map.put(key,value);
}
public synchronized int usedEntries() {
    return map.size();
}
public synchronized void clear() {
    map.clear();
}
public synchronized Collection<Map.Entry<K, V>> getAll() {
    return new ArrayList<Map.Entry<K, V>>(map.entrySet());
}
}
复制代码

If herein by reference https://juejin.im/post/5a4b433b6fb9a0451705916f infringement, immediately notify processing

Guess you like

Origin juejin.im/post/5d3c4180e51d454f6f16ece7