VOOZH about

URL: https://www.geeksforgeeks.org/java/java-enumset-range-method/

⇱ Java EnumSet range() Method - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Java EnumSet range() Method

Last Updated : 22 May, 2025

The EnumSet.range() method is a part of the java.util package. This method is used to create an EnumSet that contains all enum constants between the specified start and end points, and it should be inclusive. It easily creates a subset of enum constants within a specified range.

Syntax of EnumSet range() Method

EnumSet<E> range(E start_point, E end_point)

Parameters: The method accepts two parameters of the object type of enum:

  • start_point: This refers to the starting element that needs to be added to the enum set.
  • end_point: This refers to the last element that needs to be added to the enum set.

Return Value: The method returns the enum set created by the elements mentioned within the specified range. 

Exceptions: The method throws two types of exceptions:

  • NullPointerException is thrown if any of the starting or the last element is NULL.
  • IllegalArgumentException is thrown when the first element is greater than the last element with respect to the position.

Examples of Java EnumSet range() Method

Example 1: In this example, we will create an EnumSet using the range() method with the GFG enum.


Example 2: In this example, we will use the range() method with a different enum called CARS.


Important Points:

  • This method is type-safe. This means we can only include enum constants of the specified enum type.
  • This method is very useful for creating a subset of enum constants within a specific range without manually adding each one.
Comment
Article Tags:
Article Tags: