What is the EnumMap.put() method in Java?
EnumMap is similar to Map, except that EnumMap only takes the Enum type as a key. Additionally, all the keys in the EnumMap must be from a single Enum type.
The put() method of the EnumMap class:
-
Adds a new key-value mapping if there is no mapping already present for the passed key.
-
Updates the value of the key-value mapping if there is a mapping present for the passed key.
Syntax
public V put(K key,V value)
Parameters
-
key: This is the key for which the value is to be mapped. -
value: This is the value that needs to be associated with the key.
Return value
If the key is already present in the hashtable, then the old value is replaced with the passed value, and the old value is returned.
If the key is not present in the map, a new key-value pair is inserted and null is returned.
Note: The
nullreturn can also indicate that the previousnullvalue is associated with the passed key.
Code
The code below demonstrates how we can use the put() method:
import java.util.EnumMap;class Gett {enum Days{MON, TUE, WED, THUR, FRI, SAT, SUN};public static void main( String args[] ) {EnumMap<Days, String> map = new EnumMap<>(Days.class);map.put(Days.MON, "chest");System.out.println("The map is : " + map);System.out.println("Adding the entry (Days.MON-'shoulder'). The return value is " + map.put(Days.MON, "shoulder"));System.out.println("Adding the entry (Days.TUE-'leg'). The return value is " + map.put(Days.TUE, "leg"));}}
Explanation
-
Line 1: We import the
EnumMapclass. -
Line 3: We create an
Enumfor the days of the week with the nameDays. -
Line 7: We create an
EnumMapobject with the namemap. -
Line 8: We use the
put()method to add a mapping ({Days.MON="chest"}) to themapobject. -
Line 9: We use the
put()method with the keyDays.MONand the valueshoulder. There is already another value mapped to the keyDays.MON. Hence, theput()method will replace the old value (“chest”) with the new value (“shoulder”) and return the old value (“chest”). -
Line 10: We use the
put()method with the keyDays.TUEand the valueleg. There is no value mapped to the keyDays.TUE. Hence, theput()method adds a new mapping, {Days.TUE - leg}, to the map.