What is the EnumMap.clear() method in Java?
EnumMap is similar to Map, except EnumMap only takes the Enum type as a key. Also, all the keys must be from a single Enum type.
The clear() method of the EnumMap class removes all of the key and value mappings from a specified EnumMap object. When we call this method, the EnumMap object becomes empty.
Syntax
public void clear()
This method doesn’t take any parameters and does not return a value.
Code
The code below shows how we can use the clear() method.
import java.util.EnumMap;class Clear {enum Days{MON, TUE, WED, THUR, FRI, SAT, SUN};public static void main( String args[] ) {EnumMap<Days, String> gymSchedule = new EnumMap<>(Days.class);gymSchedule.put(Days.MON, "chest");gymSchedule.put(Days.TUE, "shoulder");gymSchedule.put(Days.WED, "arms");System.out.println( "The map is" + gymSchedule);gymSchedule.clear();System.out.println( "\nAfter calling clear metthod.\nThe map is" + gymSchedule);}}
Code explanation
-
Line 1: We import the
EnumMapclass. -
Line 3: We create an
enumnamedDaysfor the days of the week. -
Lines 7 to 11: We create an
EnumMapobject and use theput()method to add three mappings (Days.MON="chest", Days.MON="shoulder", Days.WED="arms") to themap. -
Line 12: We use the
clear()method to remove all mappings from themap. This makes themapempty. -
Line 13: We print the
mapto ensure that it’s empty.