javaenumsenumsetenum-map

What are the practical scenarios do we need EnumSet and EnumMap?


I am new to Enum. While I am learning Enum, I came across EnumSet and EnumMap. I understand that when dealing with map and set using EnumSet and EnumMap is much better than the hashing counterparts from this question.

Why an EnumSet or an EnumMap is likely to be more performant than their hashed counterparts?

My question is

In what scenarios do we need Map and Set for Enum in Java?

I am more interested in knowing practical scenarios.


Solution

  • Consider a scenario where you are defining flyweight for each shape object like:

    public enum SHAPE {
        TRIANGLE, RECTANGLE, SQUARE, HEXAGON;
    }
    

    And let's assume object creation for all these shapes everytime is huge. Say it goes into DB and fetches some data say in constructor. What you do?

    You save it in a map using enum key and value as one time object and then using enum, you say try and call something like:

    public double calculateArea(SHAPE shape) {
        Figure figure = map.get(shape);//you dont create object but take it from a map
        return figure.calculate();
    }
    

    For EnumSet, consider you have enum with basic colors like:

    enum COLORS {
        RED, BLUE, GREEN
    }
    

    Now if i want to create say YELLOW Color and wish to know the INGREDIENTS for the same, i could use EnumSet with two Colors like GREEN and RED. Similarly, i could store multiple set with variations as per my color requirements.

    This is just for example purpose, but you could even add count to make it more complex to say how much of RED, BLUE, GREEN pixel variation you need.