EnumSet and EnumMap
EnumSet
EnumSet
is a Set implementation specifically designed for use with enum types. It is a highly optimized collection that is more efficient than HashSet
when dealing with enums.
Features of EnumSet
EnumSet
Specialized for Enums: It can only store enum values.
Efficient: It uses bit vectors internally, making it much faster and more memory efficient than
HashSet
when working with enums.No Null Values: It does not allow
null
elements. Attempting to addnull
will throw aNullPointerException
.Order: The order of the enum constants in the
EnumSet
is determined by their natural order (the order in which the constants are declared in the enum class). We can also use a specific ordering by providing a comparator.
Methods in EnumSet
:
EnumSet
:EnumSet.of(E... elements)
: Creates anEnumSet
with the specified enum constants.EnumSet.allOf(Class<E> elementType)
: Creates anEnumSet
containing all constants of the specified enum class.EnumSet.noneOf(Class<E> elementType)
: Creates an emptyEnumSet
.EnumSet.copyOf(Collection<? extends E> c)
: Creates anEnumSet
containing all of the elements in the specified collection that are also enum constants of the same type.
EnumMap
EnumMap
is a Map implementation that uses enum constants as keys. It is optimized for use with enums as keys and provides superior performance over regular HashMap
when the keys are enums.
Features of EnumMap
:
EnumMap
:Specialized for Enums: The keys in an
EnumMap
must be enum constants.Efficient: It is faster and uses less memory than a
HashMap
when the keys are enums, because it internally stores the mappings in an array, making lookups and insertions much faster.Ordering: The map is ordered based on the natural order of the enum constants (the order in which the constants are defined).
Null Keys Not Allowed: It does not allow
null
keys. However,null
values are allowed.
Methods in EnumMap
:
EnumMap
:EnumMap(Class<K> keyType)
: Creates an emptyEnumMap
with the specified enum type as the key.EnumMap.put(K key, V value)
: Adds a key-value pair to the map.EnumMap.get(Object key)
: Retrieves the value associated with the given key.EnumMap.remove(Object key)
: Removes the entry for the specified key.
Comparison of EnumSet
vs EnumMap
:
EnumSet
vs EnumMap
:Feature
EnumSet
EnumMap
Type
A Set
of enum values
A Map
where keys are enum values
Null Handling
Does not allow null
elements
Does not allow null
keys, but allows null
values
Usage
Used when you need a collection of enum values without duplicates
Used when you need to associate values with enum constants
Efficiency
More memory-efficient and faster than HashSet
More memory-efficient and faster than HashMap
for enums as keys
Ordering
Follows the natural order of enum constants
Follows the natural order of enum constants
Last updated
Was this helpful?