Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limiting the max size of a HashMap in Java

Tags:

java

hashmap

I want to limit the maximum size of a HashMap to take metrics on a variety of hashing algorithms that I'm implementing. I looked at the loadfactor in one of HashMap's overloaded constructors.

HashMap(int initialCapacity, float loadFactor)  

I tried setting the loadFactor to 0.0f in the constructor (meaning that I don't want the HashMap to grow in size EVER) but javac calls this invalid:

Exception in thread "main" java.lang.IllegalArgumentException: Illegal load factor: 0.0         at java.util.HashMap.<init>(HashMap.java:177)         at hashtables.CustomHash.<init>(Main.java:20)         at hashtables.Main.main(Main.java:70) Java Result: 1 

Is there another way to limit the size of HashMap so it doesn't grow ever?

like image 478
andandandand Avatar asked Apr 08 '11 22:04

andandandand


People also ask

What is the max limit of HashMap in Java?

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.

Can you set the size of a HashMap in Java?

HashMap size() Method in Java util. HashMap. size() method of HashMap class is used to get the size of the map which refers to the number of the key-value pair or mappings in the Map.

Does HashMap have a limit?

There is no theoretical limit, but there is a limit of buckets to store different entry chains (stored under a different hashkey).


2 Answers

You could create a new class like this to limit the size of a HashMap:

public class MaxSizeHashMap<K, V> extends LinkedHashMap<K, V> {     private final int maxSize;      public MaxSizeHashMap(int maxSize) {         this.maxSize = maxSize;     }      @Override     protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {         return size() > maxSize;     } } 
like image 176
WhiteFang34 Avatar answered Sep 19 '22 20:09

WhiteFang34


Sometimes simpler is better.

public class InstrumentedHashMap<K, V> implements Map<K, V> {      private Map<K, V> map;      public InstrumentedHashMap() {         map = new HashMap<K, V>();     }      public boolean put(K key, V value) {         if (map.size() >= MAX && !map.containsKey(key)) {              return false;         } else {              map.put(key, value);              return true;         }     }      ... } 
like image 23
Mike Avatar answered Sep 22 '22 20:09

Mike