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 EnumSet class.

  • In line 3: We create an Enum with the name Size.

  • In line 7: We use the allOf method to create a new EnumSet object. The returned object will contain all of the elements in the specified element type. In our case, the returned set contains all the elements of the Size enum.

  • In line 9: We use the size method to get the number of elements present in the set. In our case, the code will return 4.

Free Resources