Java Utility Library

Java EnumSet - of() Method



The java.util.EnumSet.of() method is used to create an enum set initially containing the specified elements.

Syntax

public static <E extends Enum<E>> EnumSet<E> of(E first,
                                                E... rest)

Here, E is the type of element maintained by the container.

Parameters

first Specify an element that the set is to contain initially.
rest Specify the remaining elements the set is to contain initially.

Return Value

Returns an enum set initially containing the specified elements.

Exception

Throws NullPointerException, if any of the specified elements are null, or if rest is null.

Example:

In the example below, the java.util.EnumSet.of() method is used to create an enum set initially containing the specified elements.

import java.util.*;

public class MyClass {
  
  //creating an enum
  public enum weekday{
    SUN, MON, TUE, WED, THU, FRI, SAT
  }

  public static void main(String[] args) {
    //creating a list which will be used as argument
    weekday[] MyList = {weekday.THU, weekday.FRI};

    //calling the other_main method
    other_main(MyList);
  }

  public static void other_main(weekday[] List) {
    //creating an EnumSet
    EnumSet<weekday> Set;

    //Adding first element and rest of elements
    Set = EnumSet.of(weekday.SUN, List);

    //print the content of EnumSet
    System.out.println("Set contains: "+ Set);  
  }  
}

The output of the above code will be:

Set contains: [SUN, THU, FRI]

❮ Java.util - EnumSet