Java EnumMap
In Java, EnumMap
is a class that implements the Map
interface and is designed to be used with enum types as keys. It is part of the java.util
package and provides a highly optimized implementation for mapping enums to values.
EnumMap
is similar to other Map
implementations, such as HashMap
or TreeMap
, but it is designed to take advantage of the fact that enums have a fixed number of values and can be efficiently represented as arrays. By using arrays internally, EnumMap
can provide better performance and reduced memory overhead compared to other Map
implementations.
Here are some of the most commonly used methods in the EnumMap
class:
void clear()
: This method removes all the key-value mappings from theEnumMap
.boolean containsKey(Object key)
: This method returnstrue
if theEnumMap
contains a mapping for the specified key, otherwisefalse
.boolean containsValue(Object value)
: This method returnstrue
if theEnumMap
contains one or more mappings to the specified value, otherwisefalse
.Set<Map.Entry<K, V>> entrySet()
: This method returns aSet
view of the key-value mappings in theEnumMap
.V get(Object key)
: This method returns the value to which the specified key is mapped, ornull
if the key is not mapped to any value.boolean isEmpty()
: This method returnstrue
if theEnumMap
contains no key-value mappings, otherwisefalse
.Set<K> keySet()
: This method returns aSet
view of the keys in theEnumMap
.V put(K key, V value)
: This method associates the specified value with the specified key in theEnumMap
. If theEnumMap
previously contained a mapping for the key, the old value is replaced with the new value and the old value is returned.void putAll(Map<? extends K, ? extends V> m)
: This method copies all of the mappings from the specifiedMap
to thisEnumMap
.V remove(Object key)
: This method removes the mapping for the specified key from theEnumMap
, if it is present.int size()
: This method returns the number of key-value mappings in theEnumMap
.Collection<V> values()
: This method returns aCollection
view of the values in theEnumMap
.
The keys in an EnumMap
must be instances of the same enum type, and the values can be of any type. When an EnumMap
is created, it must be initialized with all the possible keys of the enum type, which allows the EnumMap
to be implemented as an array internally. This means that EnumMap
can provide constant-time performance for most operations, making it a highly efficient choice for mapping enums to values.