Java EnumSet allOf() Method



Description

The java.util.EnumSet.allOf(Class<E> elementType) method creates an enum set containing all of the elements in the specified element type.

Declaration

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

public static <E extends Enum<E>> EnumSet<E> allOf(Class<E> elementType)

Parameters

elementType − the class object of the element type for this enum set

Return Value

This method does not return a value.

Exception

NullPointerException − if elementType is null

Creating Enumset from All Values of an Enum Example

The following example shows the usage of Java EnumSet allOf() method to populate the EnumSet instance. We've created a enum Numbers. Then a EnumSet instance is created. Using allOf() method, enumSet is populated with values of enum and resulted enumSet is printed.

package com.tutorialspoint;

import java.util.EnumSet;

public class EnumSetDemo {

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

   public static void main(String[] args) {

      // create an empty EnumSet 
      EnumSet<Numbers> set = null;

      // print the set
      System.out.println(set);

      // create the set by getting all elements from Numbers
      set = EnumSet.allOf(Numbers.class);

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

Output

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

null
Updated set:[ONE, TWO, THREE, FOUR, FIVE]

Creating Enumset from All Values of an Enum with Value Example

The following example shows the usage of Java EnumSet allOf() method to populate the EnumSet instance. We've created a enum Numbers which accepts a value to be assigned to the enum. Then a EnumSet instance is created. Using allOf() method, enumSet is populated with values of enum and resulted enumSet is printed.

package com.tutorialspoint;

import java.util.EnumSet;

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 an empty EnumSet 
      EnumSet<Number> set = null;

      // create the set by getting all elements from Numbers
      set = EnumSet.allOf(Number.class);

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

Output

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

Updated set:[ONE(1), TWO(2), THREE(3), FOUR(4), FIVE(5)]
java_util_enumset.htm
Advertisements