Java – HashMap class

Previous
Next

Map interface:  The implementations are

  1. HashMap
  2. LinkedHashMap
  3. TreeMap

Note : HashMap and LinkedHashMap stores the elements according to Hashtable algorithm only.

  • In Map interface, elements will be stored using keys.
  • Keys are always unique(duplicates not allowed).
  • Keys are also objects.
  • Duplicate elements are allowed with unique keys.
  • “null” key is allowed in HashMap and LinkedHashMap.
  • “null” object is also allowed.
  • It is allowed to store the elements with heterogenous keys(but unique).
  • Duplicates will be replaced but not rejected.

HashMap :

  • available in util package
  • since from jdk 1.2
  • not ordered
  • duplicates allowed with unique keys
  • default capacity is 16
  • default load factor is 0.75
  • HashMap is not synchronized by default. but can be synchronized explicitly as follows.

Collections.synchronizedMap(new HashMap(…));

import java.util.*;
class SetDemo 
{
	public static void main(String[] args)
	{
		HashSet hs = new HashSet();
		hs.add("one");	
		if(hs.add("one"))
			System.out.println("Duplicate element is replaced in Set");
		else
			System.out.println("Duplicate element is rejected in Set");
	}
}

Set Object reject the duplicates where as Map object replace the existing object.

import java.util.HashMap ;
class MapDemo 
{
	public static void main(String[] args) 
	{
		HashMap map = new HashMap();

		map.put(10 , "One");
		System.out.println("Map : "+map);

		map.put(10 , "Two"); // replace existing element
		System.out.println("Map : "+map);
	}
}

We can store any type of keys as well as elements into map object.

import java.util.HashMap ;
class MapDemo 
{
	public static void main(String[] args) 
	{
		HashMap map = new HashMap();

		map.put(10 , "One");
		map.put(20 , "One");
		map.put(null , "Two");
		map.put("key" , "Three");
		map.put(34.56 , "Four");
		System.out.println("Map : "+map);
	}
}

Note : we can apply generics on map collection object. Once we set restrictions on data, all the methods logic will be converted according to generics type.

import java.util.HashMap ;
class MapDemo 
{
	public static void main(String[] args) 
	{
		HashMap<Integer , String> map = new HashMap<Integer, String>();
		map.put(10 , "One");
		map.put(34.56 , "Four"); // Error : Only Integer keys allowed
		System.out.println("Map : "+map);
	}
}
Previous
Next

Add Comment

Courses Enquiry Form