HashMap in Java

Posted on Updated on

HashMap implements Map and extends AbstractMap.  It does not add any methods of its own. It is most common class used and its implementation is based on Hashtable. You can find different ways to iterate a HashMap in our tutorial how to iterate a Map in Java.

Listed below are the features of HashMap.

  1. It stores key-value pairs.
  2. It contains unique key.
  3. HashMap allows one null key and multiple null values.
  4. Insertion order is not maintain in HashMap.
  5. HashMap allows the execution time of basic operations, such as get( ) and put( ), to remain constant even for large sets.

HashMap provides following constructors.

Constructor Description
HashMap() Default construtor.
HashMap(Map m) Creates object of the HashMap by using the elements of m.
HashMap(int capacity) Creates object of HashMap with initial capacity.
HashMap(int capacity, float fillRatio) Creates object of HashMapwith initial capacity and fillRatio. The fill ratio must be between 0.0 and 1.0.

Load Factor/Fill Ratio

Load Factor determines how full the HashMap can be before it is resized upward. when the number of elements is greater than the capacity of the HashMap multiplied by its load factor/fill ratio, the HashMap is expanded. Default value of load factor is 0.75.

Output :

Using Iterator
Key : 1 Value :New York
Key : 2 Value :London
Key : 3 Value :Paris
Key : 4 Value :Mumbai
Iterate using keySet
Key : 1 Value : New York
Key : 2 Value : London
Key : 3 Value : Paris
Key : 4 Value : Mumbai

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.