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 e1, 
                                                E e2, E e3)

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

Parameters

e1 Specify an element that this set is to contain initially.
e2 Specify another element that this set is to contain initially.
e3 Specify another element that this set is to contain initially.

Return Value

Returns an enum set initially containing the specified elements.

Exception

Throws NullPointerException, if any parameters are 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 an EnumSet
    EnumSet<weekday> Set;

    //Add elements using of() method
    Set = EnumSet.of(weekday.SUN, weekday.MON, weekday.TUE);
    
    //print the content of Set
    System.out.println("Set contains: "+ Set);  

    //Add another set of elements using of() method
    //which replaces the previous elements
    Set = EnumSet.of(weekday.WED, weekday.THU, weekday.FRI);

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

The output of the above code will be:

Set contains: [SUN, MON, TUE]
Set contains: [WED, THU, FRI]

❮ Java.util - EnumSet