Friday, October 31, 2014

HashMap Constructors

Over a couple of blogs from now, I wil try answer the questions that I have mentioned here.
This is the answer to question number 4.
When we create a new hashmap we generally use a no-arg constructor
Hashmap h = new Hashmap(); 
So, what arguments can the hashmap constructor accept?

Answer:

Hashmap has the following constructors:

a) HashMap()
     Constructs an empty HashMap with the default initial capacity (16) and the default load factor (0.75).
b) HashMap(int initialCapacity)
Constructs an empty HashMap with the specified initial capacity and the default load factor (0.75).
c) HashMap(int initialCapacity, float loadFactor)
Constructs an empty HashMap with the specified initial capacity and load factor.
d) HashMap(Map<? extends K,? extends V> m)
Constructs a new HashMap with the same mappings as the specified Map.

Where, initial capacity is the starting number of entries which can be put in a Hashmap ie the capacity of the hashmap as soon as it is created.
I assume you know that Hashmap doubles its capacity after getting filled upto a certain %. This % is nothing but load factor. The default value is 0.75. However, this can be changed. So as soon as the hashmap gets filled to that percentage, it increases its capacity using rehashing technique.