Map and HashMap in Java

Hash table based implementation of the Map interface. This implementation provides all of the optional map operations, and permits null values and the null key. It contains only unique elements. It may have one null key and multiple null values. It maintains no order.

Map is interface and hashmap is class. All the properties of Map, discussed earlier, are attained by HashMap.

HashMap<String, Object> map1 = new HashMap<String, Object>();

Map<String, Object> map2 = new HashMap<String, Object>();

First of all Map is an interface it has different implementation like - HashMap, TreeHashMap, LinkedHashMap etc. Interface works like a super class for the implementing class. So according to OOP's rule any concrete class that implements Map is a Map also. That means we can assign/put any HashMap type variable to a Map type variable without any type of casting.

In this case we can assign map1 to map2 without any casting or any losing of data –


Map having following implementations,

HashMap                 Map m = new HashMap();

LinkedHashMap     Map m = new LinkedHashMap();

Tree Map                 Map m = new TreeMap();

WeakHashMap      Map m = new WeakHashMap();  

import java.util.HashMap;


public class Sample {

     static HashMap<Integer, String> myMap;


     public static void main(String args[]) {

          myMap = new HashMap<Integer, String>();

          // add data to haspmap

          myMap.put(101, "Zack");

          myMap.put(102, "Jooli");

          myMap.put(103, "David");

          myMap.put(104, "Rusell");

          myMap.put(105, "Robin");


          // find data from haspmap by key


         //if record not found then return null.





What is difference between HashSet and HashMap?

·         HashSet contains only values whereas HashMap contains entry (key and value).

·         Hashtable is synchronized, whereas HashMap is not. This makes HashMap better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones. 

·         Hashtable does not allow null keys or values.  HashMap allows one null key and any number of null values. 

·         One of HashMap's subclasses is LinkedHashMap, so in the event that you'd want predictable iteration order (which is insertion order by default), you could easily swap out the HashMap for a LinkedHashMap. This wouldn't be as easy if you were using Hashtable.

  Modified On Nov-16-2017 11:51:59 PM

Leave Comment