Need of EnumSet / EnumMap over generified Set / Map

880 Views Asked by At

EnumSet/EnumMap can be created by specifying the defined enum to produce set/map instance as shown in below sample code.

So far I read, difference between EnumSet/EnumMap with that of Set/Map is that we cannot add objects other than the specified Enumin the EnumSet/EnumMap. If this is the case, then just the generified Set/Map itself will be enough, isn't it?

Please find the EnumSet/EnumMap and their respective generified Set/Map as follows,

enum Value {
    VALUE_1, VALUE_2, VALUE_3
};

public class Sample {   
    public static void main(String args[]) {
        EnumSet<Value> enumSet = EnumSet.of(Value.VALUE_1);

        Set<Value> enumGenerifiedSet = new HashSet<Value>();
        enumGenerifiedSet.add(Value.VALUE_1);

        EnumMap<Value, Integer> enumMap = new EnumMap<Value, Integer>(Value.class);
        enumMap.put(Value.VALUE_1, 1);

        Map<Value, Integer> enumGenerifiedMap = new HashMap<Value, Integer>();
        enumGenerifiedMap.put(Value.VALUE_1, 1);
    }
}

So can you please tell me what is the need of having EnumSet/EnumMap eventhough we can able to create the set/map that is generified to the defined Enum?

Thanks in advance.

1

There are 1 best solutions below

0
On

The interfaces are nearly identical. Though, the performance and the underlying mechanisms are completely different.

The documentation is pretty clear on this:

Enum sets are represented internally as bit vectors. This representation is extremely compact and efficient. The space and time performance of this class should be good enough to allow its use as a high-quality, typesafe alternative to traditional int-based "bit flags." Even bulk operations (such as containsAll and retainAll) should run very quickly if their argument is also an enum set.

[...]

null elements are not permitted. Attempts to insert a null element will throw NullPointerException. Attempts to test for the presence of a null element or to remove one will, however, function properly.

[...]

Implementation note: All basic operations execute in constant time. They are likely (though not guaranteed) to be much faster than their HashSet counterparts. Even bulk operations execute in constant time if their argument is also an enum set.

java.util.EnumSet, JDK 11