Difference Between EnumMap and EnumSet in Java
EnumMap and EnumSet both are the classes defined inside the java collection. In this article, we will learn the differences between EnumMap and EnumSet. EnumMap is the specialized implementation of the Map interface and the EnumSet is the specialized implementation of the Set interface. There are some differences that exist between them. So we have tried to list out the differences between EnumMap and EnumSet.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
- EnumMap is much faster than HashMap.
- EnumMap class is a member of the Java Collections Framework.
- EnumMap is an ordered collection maintained in the natural order of their keys.
- All keys of each EnumMap instance must be keys of the same enum type.
- EnumMap doesn’t allow inserting a null key if we try to insert the null key, it will throw NullPointerException.
- EnumMap internally represented as arrays for better performance.
Below is the implementation of the EnumMap:
Size of EnumMap: 4 Apple 1 Mango 2 Orange 3 Banana 4
- EnumSet class is a member of the Java Collections Framework and it is not synchronized.
- All the elements in an EnumSet must come from a single enumeration type that is specified when the set is created either explicitly or implicitly.
- EnumSet is much faster than HashSet.
- EnumSet doesn’t allow inserting null object if we try to insert the null object, it will throw NullPointerException.
Below is the implementation of the EnumSet:
EnumSet : Monday Tuesday
Difference between EnumMap and EnumSet
|EnumMap is a specialized implementation of the Map interface for the enumeration types.||EnumSet is a specialized implementation of the Set interface for the enumeration types.|
|EnumMap is internally represented as an array.||EnumSet is internally represented as a BitVector.|
|EnumMap doesn’t allow to insert the null keys, however, null values can be inserted.||EnumSet doesn’t allow inserting null elements.|
|EnumMap is not an abstract class.||EnumSet is an abstract class.|
|EnumMap is not an abstract class therefore, we can create an instance of this class.||EnumSet is an abstract class therefore, we can not create the instance of this class.|