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.
public void clear()
This method doesn’t take any parameters and does not return a value.
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);}}
Line 1: We import the EnumMap
class.
Line 3: We create an enum
named Days
for the days of the week.
Lines 7 to 11: We create an EnumMap
object and use the put()
method to add three mappings (Days.MON="chest", Days.MON="shoulder", Days.WED="arms"
) to the map
.
Line 12: We use the clear()
method to remove all mappings from the map
. This makes the map
empty.
Line 13: We print the map
to ensure that it’s empty.