Difference between EnumMap and HashMap in Java

JavaObject Oriented ProgrammingProgramming

EnumMap is introduced in JDK5. It is designed to use Enum as key in the Map. It is also the implementation of the Map interface. All of the key in the EnumMap should be of the same enum type. In EnumMap , key can’t be null and any it will throw NullPointerException.

As per java docs −

 EnumMap internally using as arrays, this representation is extremely compact and efficient.

HashMap is also the implementation of the Map interface. It is used to store the data in Key and Value form. It can contain one null key and multiple null values . In HashMap, keys can’t be a primitive type. Java HashMap implementation provides constant-time performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets. 

Sr. No.
Key
EnumMap
HashMap

1

Basic 

A specialized Map implementation for use with enum type keys

HashMap is also the implementation of the Map interface.

2

Null Key

It can’t have null key.

 It can have one null key and multiple null values

3

Performance 

All operations execute in constant time therefore it is faster than HashMap 

It is slower than HashMap

4. 

Internal Implementation 

It uses Array internally 

It uses Hashtable internally 

5.

Ordering 

EnumMap stores keys in the natural order of their keys

HashMap is not ordered

Example of EnumMap

import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
public class EnumMapExample {
   public enum LaptopEnum {
      HCL, DELL, IBM
   };
   public static void main(String[] args) {
      // create enum map
      EnumMap map = new EnumMap(LaptopEnum.class);
      map.put(LaptopEnum.HCL, "100");
      map.put(LaptopEnum.DELL, "200");
      map.put(LaptopEnum.IBM, "300");
      // print the map
      for (Map.Entry m : map.entrySet()) {
         System.out.println(m.getKey() + " " + m.getValue());
      }
   }
}

Example of HashMap

import java.util.ArrayList;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HashMapExample {
   public static void main(String[] args) {
      // create Hash map
      Map map = new HashMap();
      map.put("HCL", "100");
      map.put("DELL", "200");
      map.put("IBM", "300");
      // print the map
      for (Map.Entry m : map.entrySet()) {
         System.out.println(m.getKey() + " " + m.getValue());
      }
   }
}
raja
Published on 21-Jan-2020 07:59:49
Advertisements