In Java, you can create a new HashMap
to hold a specific number of items like so:
Map m = new HashMap(100);
Guava provides a Maps.newHashMapWithExpectedSize(int)
method, which I would expect to simply call HashMap(int)
. But it doesn't do this, instead it calculates its own capacity and uses that.
Why does newHashMapWithExpectedSize
do its own thing, and why would I want to use it over calling new HashMap(int)
directly?
HashMap is a non-synchronized class of the Java Collection Framework that contains null values and keys, whereas Map is a Java interface, which is used to map key-pair values.
HashMap is faster than Map since it does not keep track of the order in which its components are inserted. HashMap, unlike Map, can hold duplicate values. It's feasible to use the Map interface implementing classes to implement it. HashMap, on the other hand, is all about implementing the Map interface.
HashMap<K, V> is a part of Java's collection since Java 1.2. This class is found in java. util package. It provides the basic implementation of the Map interface of Java. It stores the data in (Key, Value) pairs, and you can access them by an index of another type (e.g. an Integer).
Have you read the method's Javadoc?
Creates a
HashMap
instance, with a high enough "initial capacity" that it should holdexpectedSize
elements without growth.
Note that the new HashMap(int)
constructor's "initial size" parameter specifies the initial size of the hash table that entries are stored in, which is basically an implementation detail that you shouldn't have to care about. The hash table will resize when it exceeds the map's load factor (which defaults to 0.75), which means that if you specify an initial capacity of 16 and then add 16 entries to the map, the hash table will almost certainly be resized.
With Guava's method, if you specify an expected size of 16 and then add 16 entries, the hash table should not resize.
The HashMap constructor argument is the capacity of the map, i.e. the number of buckets.
So, if you pass 10 as argument, and store 8 keys in the map, the rehash threshold (75% by default) will be reached and the map will rehash.
On the other hand, the argument passed to newHashMapWithExpectedSize() is the expected size of the map. So if you pass 10, Guava will create a map with enough buckets to make sure the map doesn't rehash when inserting 10 elements: at least 14 buckets.
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