Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limited size hash map

Tags:

java

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?

like image 422
Phate Avatar asked Sep 07 '12 14:09

Phate


People also ask

What is the size of HashMap?

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.

What is the highest limit of HashMap?

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.

What is default size of HashMap?

Constructs an empty HashMap with the default initial capacity (16) and the default load factor (0.75).

How do I create a custom HashMap?

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).


2 Answers

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.

like image 126
jarnbjo Avatar answered Sep 20 '22 18:09

jarnbjo


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

like image 30
Peter Lawrey Avatar answered Sep 16 '22 18:09

Peter Lawrey