What is the EnumMap.size() method in Java?
EnumMap is similar to Map except that EnumMap only takes the Enum type as key. Also, all the keys must be from a single enum type. For further details refer here.
The size() method of EnumMap will return the number of key-value mappings present in this map.
Syntax
public int size()
Argument
This method doesn’t take any argument.
Return value
This method returns an integer value denoting the number of mappings present in the map.
Code
The example below shows how to use the size() method:
import java.util.EnumMap;class Size {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");map.put(Days.TUE, "leg");System.out.println( "The map is : " + map);System.out.println( "The size is : " + map.size());}}
Explanation
In the above code:
-
In line 1, we import the
EnumMapclass. -
In line 3, we have created an
enumfor days of the week with the nameDays. -
In line 7, we create an
EnumMapobject with the namemap. -
In lines 8-9, we use the
put()method to add two mappings{Days.MON="chest",Days.TUE="leg"}to themapobject. -
In line 11, we use the
sizemethod to get the number of key-value mappings present in. themap. We get2as result.