Difference Between EnumMap and EnumSet in Java


In Java, EnumMap and EnumSet are two specialized classes that give effective ways to work with counted sorts. Both EnumMap and EnumSet are portion of the Java Collections System and offer particular highlights for taking care of collections of enum components. In this article, we'll explore the contrasts between EnumMap and EnumSet, their sentence structure, and how they can be utilized in totally diverse scenarios.

Syntax

Before going into the details, let's first understand the basic syntax of EnumMap and EnumSet in Java −

EnumMap syntax

EnumMap<EnumClass, ValueType> map = new EnumMap<>(EnumClass.class);

EnumSet syntax

EnumSet<EnumClass> set = EnumSet.<EnumClass>of(EnumValue1, EnumValue2, ...);

Explanation of Syntax

EnumMap − The EnumMap class is parameterized with two types. The first type is the enum class itself, specifying the type of keys in the map. The moment sort is the esteem sort related with each key.

EnumSet − The EnumSet lesson is parameterized with the enum course and speaks to a set of enum constants. The "of" strategy is utilized to make an EnumSet with one or more enum values indicated as contentions.

Approach 1: EnumMap

The EnumMap class in Java is specifically designed to store enum constants as keys and corresponding values. It is implemented as an array of values, indexed by the ordinal values of the enum constants. This implementation provides efficient and constant time performance for basic operations like get and put.

Algorithm for Approach 1

  • Create an EnumMap instance by specifying the enum class.

  • Add key-value pairs to the EnumMap using the put() method.

  • Retrieve values from the EnumMap using the get() method.

  • Perform other operations like size(), containsKey(), etc., as required.

Example

import java.util.EnumMap;

public class EnumMapExample {
   enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }

   public static void main(String[] args) {
      EnumMap<Day, String> tasks = new EnumMap<>(Day.class);

      tasks.put(Day.MONDAY, "Meeting");
      tasks.put(Day.TUESDAY, "Presentation");
      tasks.put(Day.WEDNESDAY, "Code review");
      
      System.out.println("Task for Tuesday: " + tasks.get(Day.TUESDAY));
      System.out.println("Number of tasks: " + tasks.size());
   }
}

Output

Task for Tuesday: Presentation
Number of tasks: 3

Explanation of the Code in Approach 1

In the given code snippet, we define an enum type called "Day" representing the days of the week. We then create an EnumMap instance named "tasks" by specifying the Day class. We include key-value sets to the EnumMap utilizing the put() strategy, partner each day with an errand. At long last, we recover an esteem from the EnumMap utilizing the get() strategy and show the number of assignments utilizing the size() strategy.

Approach 2: EnumSet

EnumSet, on the other hand, is designed to represent a set of enum constants. It internally uses a bit vector to efficiently store the elements. EnumSet provides a compact and highly optimized implementation for operations such as containment checks, union, intersection, and more.

Algorithm for Approach 2

  • Create an EnumSet instance by using the "of" method and specifying the enum values.

  • Perform operations on the EnumSet like add, remove, contains, etc.

  • Apply set operations like union(), intersection(), and complement() as needed.

Example

import java.util.EnumSet;

public class EnumSetExample {
   enum Color { RED, GREEN, BLUE, YELLOW }

   public static void main(String[] args) {
      EnumSet<Color> primaryColors = EnumSet.of(Color.RED, Color.GREEN, Color.BLUE);
      EnumSet<Color> secondaryColors = EnumSet.of(Color.GREEN, Color.BLUE, Color.YELLOW);

      System.out.println("Primary colors: " + primaryColors);
      System.out.println("Secondary colors: " + secondaryColors);

      EnumSet<Color> allColors = EnumSet.allOf(Color.class);
      EnumSet<Color> commonColors = EnumSet.copyOf(primaryColors);
      commonColors.retainAll(secondaryColors);

      System.out.println("All colors: " + allColors);
      System.out.println("Common colors: " + commonColors);
   }
}

Output

Primary colors: [RED, GREEN, BLUE]
Secondary colors: [GREEN, BLUE, YELLOW]
All colors: [RED, GREEN, BLUE, YELLOW]
Common colors: [GREEN, BLUE]

Explanation of the Code in Approach 2

In this code illustration, we characterize an enum sort called "Color" speaking to diverse colors. We make two EnumSet occurrences, "primaryColors" and "secondaryColors," utilizing the "of" strategy and indicating the enum values. We at that point perform different operations on the EnumSets, such as printing their substance, making an EnumSet containing all colors, and finding the common colors between the two sets.

Difference Between EnumMap and EnumSet in Java

EnumMap

EnumSet

Represents a mapping between enum constants and values.

Represents a set of enum constants.

Efficient for associating values with enum constants.

Efficient for working with sets of enum values.

Implements the Map interface.

Implements the Set interface.

Internally implemented as an array of values indexed by the ordinal values of enum constants.

Internally implemented using a bit vector for efficient storage.

Provides constant time performance for basic operations like get and put.

Provides optimized performance for set operations like containment checks, union, intersection, etc.

Conclusion

In rundown, EnumMap and EnumSet are specialized classes in Java that offer productive ways to work with listed sorts. EnumMap provides a mapping between enum constants and values, while EnumSet represents a set of enum constants. EnumMap is ideal for scenarios where you need to associate specific values with each enum constant, whereas EnumSet is useful when you need to work with sets of enum values. Understanding the differences and features of these classes enables you to leverage their strengths and enhance your Java applications.

Updated on: 28-Jul-2023

183 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements