I'd like to make an hash map to use like a cache. Cache has an initial size, if you try inserting an item when cache is full last recently used item should be replaced...any ideas?
Initial Capacity of HashMapThe initial capacity of the HashMap is 24, i.e., 16. The capacity of the HashMap is doubled each time it reaches the threshold. The capacity is increased to 25=32, 26=64, and so on.
In Sun's JVM, HashMap uses an array which is a power of 2. The largest power of two allowed for an array size is 2^30 . And the largest number of elements you can have before the HashMap will try to double its size to 2^31 (which it cannot do) is ( 2^30 * loadFactor ) or about 700 million for the default load factor.
Constructs an empty HashMap with the default initial capacity (16) and the default load factor (0.75).
An instance of HashMap can be created with a new operator. Map<String, Integer> map = new HashMap<String, Integer>(5); Above statement creates an instance of HashMap with a default bucket size of 16(0... 15).
The most trivial approach would be to extend LinkedHashMap
, override the removeEldestEntry(Map.Entry<K,V> eldest)
method and decide in its implementation if your cache is "full" or not.
You can use a LinkedHashMap by implementing removeEldest
public static <K,V> Map<K,V> lruCache(final int maxSize) {
return new LinkedHashMap<K,V>(maxSize*4/3, 0.75f, true) {
@Override
protected boolean removeEldestEntry(Map.Entry<K,V> eldest) {
return size() > maxSize;
}
};
}
For more details
http://vanillajava.blogspot.co.uk/2011/06/java-secret-lru-cache-in-java.html
http://blog.meschberger.ch/2008/10/linkedhashmaps-hidden-features.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With