Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between new HashMap(int) and guava Maps.newHashMapWithExpectedSize(int)

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?

like image 531
thecoop Avatar asked May 13 '15 16:05

thecoop


People also ask

What is the difference between HashMap and map?

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.

Is HashMap better than map?

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.

What is HashMap in Java?

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


2 Answers

Have you read the method's Javadoc?

Creates a HashMap instance, with a high enough "initial capacity" that it should hold expectedSize 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.

like image 97
ColinD Avatar answered Oct 11 '22 20:10

ColinD


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.

like image 23
JB Nizet Avatar answered Oct 11 '22 19:10

JB Nizet