Open In App

Java EnumSet range() Method

Last Updated : 22 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

Java
// Java program to demonstrate
// EnumSet.range() method usage
import java.util.*;

// Define an enum type
enum GFG {
    Welcome, To, The, World, of, Geeks
}

public class Geeks {
    public static void main(String[] args) {
        
        // Create an EnumSet with enum constants
        // ranging from The to Geeks inclusive
        EnumSet<GFG> es = EnumSet.range(GFG.The, GFG.Geeks);
        
        // Display the EnumSet created with the range
        System.out.println("The enum set is: " + es);
    }
}


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

Java
// Java program to demonstrate EnumSet.range()
// method with a different enum
import java.util.*;

// Define another enum type
enum CARS {
    RANGE_ROVER, MUSTANG, CAMARO, AUDI, BMW
}

public class Geeks {
    public static void main(String[] args) {
        
        // Create an EnumSet with enum constants
        // ranging from RANGE_ROVER to CAMARO inclusive
        EnumSet<CARS> es 
        = EnumSet.range(CARS.RANGE_ROVER, CARS.CAMARO);
        
        // Display the EnumSet created with the range
        System.out.println("The enum set is: " + es);
    }
}


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.

Article Tags :
Practice Tags :

Similar Reads