What is the EnumSet.size method in Java?
EnumSet is similar to Set, except that EnumSet only contains the enum type as elements. All the elements must be from a single enum type. For further details on EnumSet, refer to this shot.
The size method can be used to get the number of elements present in the EnumSet object.
Syntax
public int size()
Parameters
This method doesn’t take any parameters.
Return value
The size() method returns the integer value that represents the number of elements present in the EnumSet.
Code
import java.util.EnumSet;class SizeExample {enum Size {SMALL, MEDIUM, LARGE, EXTRALARGE}public static void main( String args[] ) {EnumSet<Size> set = EnumSet.allOf(Size.class);System.out.println("The set is " + set);System.out.println("\nThe size is " + set.size());}}
Explanation
In the code above:
-
In line 1: Import the
EnumSetclass. -
In line 3: We create an
Enumwith the nameSize. -
In line 7: We use the
allOfmethod to create a newEnumSetobject. The returned object will contain all of the elements in the specified element type. In our case, the returnedsetcontains all the elements of theSizeenum. -
In line 9: We use the
sizemethod to get the number of elements present in theset. In our case, the code will return4.