EnumMap in Java
In the previous blog, we learned about WeakHashMap. If you want to learn more about it, visit WeakHashMap in Java. In this blog, we will go through another collection class i.e. EnumMap.
EnumMap
EnumMap class is a specialized implementation of Map for enum type. It extends AbstractClass and implements the Map interface. The EnumMap class keeps the keys in their natural sequence. It is not synchronized. EnumMap class cannot have null keys, if there is a null key found then it gives NullPointerException. In order to use EnumMap class we must import the package called java.util.EnumMap.
Creating EnumMap
In order to create an EnumMap we need to import the package called java.util.EnumMap.
e.g.
Methods of EnumMap
- put()
- putAll()
- get()
- entrySet()
- keySet()
- values()
- get()
- get()
- getOrDefult()
- remove()
- clear()
- size()
- isEmpty()
- containsKey()
- containsValue()
- clone()
put() method adds or inserts the specified key/value mapping to the enum map.
putAll() method adds or inserts all the elements from the specified map to this map.
Example of EnumMap using the above two methods
Output
get() method returns the value of the specified key in the enum map.
entrySet() method returns a set of all the key-value mapping of the enum map.
keySet() method returns a set view of the keys contained in the enum map.
values() method returns the view of all the values present in the entries of the enum map.
Example of EnumMap using the above methods
Output
get() method returns the value of the specified key in the map.
get() method returns the value of the specified key in the map.
The getOrDefult() method returns the value associated with the given key. If the key cannot be discovered, it returns the specified default value.
The remove() function removes or deletes the supplied values from the enum map together with the related specified.
clear() method removes all the key-value pairs of the map.
size() method returns the number of entries in the enum map.
isEmpty() method checks whether the weakhashmap is empty or not.
containsKey() method checks if the mapping for the specified key is present in the enum map. If the key is missing, it returns false.
containsValue() method checks if the specified value is present in one or more mappings of the enum map or not. If the value is not present then it returns false.
clone() method returns the copy of the EnumMap.
Example of EnumMap using the above methods
Output