A Developer Gateway To IT World...

Techie Uncle Software Testing Core Java Java Spring C Programming Operating System HTML 5 Java 8 ES6 Project

HashMap in Java

  • Hashmap is a class that implements map interface. 
  • Map interface is introduced in java 1.2 version to store key and value pair in tabular form.
  • Hashmap uses data structure hashing technique.
  • Hashing is an algorithm that converts a large String to small String that represents same String. A shorter value helps in indexing and faster searches.
  • HashSet also uses HashMap internally.
  • HashMap extends an abstract class AbstractMap that gives an incomplete implementation of Map interface and implements cloneable and serializable interface. 
  • HashMap doesn’t allow duplicate keys but allows duplicate values. 
  • That means A single key can’t contain more than 1 value but more than 1 key can contain a single value. 
  • HashMap allows null key also but only once and multiple null values. 
  • Hashmap gives no guarantees to the order of the map. 
  • It is almost similar to HashTable but is unsynchronized.

HashMap put method:

Associates the specified value with the specified key in this map. 
If the map previously contained a mapping for the key, the old value is replaced.
Specified by: put(...) in Map, Overrides: put(...) in AbstractMap
key key with which the specified value is to be associated
value value to be associated with the specified key
the previous value associated with key, or null if there was no mapping for key. (A null return can also indicate that the map previously associated null with key.)

import java.util.HashMap;

public class TestHashMap {

       public static void main(String[] args) {
             //create map object
             HashMap<Integer, String>  hm = new HashMap<>();
             hm.put(101, "Heera");
             hm.put(103, "Babu");
             hm.put(103, "SIngh");  //values will be replaced, means one key can store only one value


Sample output:

{101=Heera, 102=Babu, 103=SIngh}