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