Java EnumSet range() Method



Description

The Java EnumSet range(E from,E to) method creates an enum set initially containing all of the elements in the range defined by the two specified endpoints.

Declaration

Following is the declaration for java.util.EnumSet.range() method

public static <E extends Enum<E>> EnumSet<E> range(E from,E to)

Parameters

  • from − the first element in the range

  • to − the kast element in the range

Return Value

This method returns an enum set initially containing all of the elements in the range defined by the two specified endpoints.

Exception

  • NullPointerException − if first or last are null

  • IllegalArgumentException − if first > last

Creating EnumSet using Range on Enum Example

The following example shows the usage of Java EnumSet range(E, E) method to populate the EnumSet instance using two enum values. We've created a enum Numbers. Then a EnumSet instance is created using two enums and resulted enumSet is printed.

package com.tutorialspoint;

import java.util.*;

public class EnumSetDemo {

   // create an enum
   public enum Numbers {
      ONE, TWO, THREE, FOUR, FIVE
   };

   public static void main(String[] args) {

      // create a set
      EnumSet<Numbers> set;

      // add four element using range
      set = EnumSet.range(Numbers.TWO, Numbers.FIVE);

      // print the set
      System.out.println("Set:" + set);
   }
}

Output

Let us compile and run the above program, this will produce the following result −

Set:[TWO, THREE, FOUR, FIVE]

Creating EnumSet using Range on Enum with Value Example

The following example shows the usage of Java EnumSet range(E, E) method to populate the EnumSet instance using two enum values. We've created a enum Numbers. Then a EnumSet instance is created using two enums and resulted enumSet is printed.

package com.tutorialspoint;

import java.util.*;

public class EnumSetDemo {

   // create an enum
   public enum Number {
      ONE("1"), TWO("2"), THREE("3"), FOUR("4"), FIVE("5");

      // instance variable for enum
      private String value;

      public String getValue() {
         return this.value;
      }

      // constructor should be private or protected
      private Number(String value) {
         this.value = value;
      }

      @Override
      public String toString() {
        return this.name() +"(" + this.value + ")";
      }
   };

   public static void main(String[] args) {

      // create a set
      EnumSet<Number> set;

      // add four element using range
      set = EnumSet.range(Number.TWO, Number.FIVE);

      // print the set
      System.out.println("Set:" + set);
   }
}

Output

Let us compile and run the above program, this will produce the following result −

Set:[TWO(2), THREE(3), FOUR(4), FIVE(5)]
java_util_enumset.htm
Advertisements