Java Utility Library

Java EnumSet - copyOf() Method



The java.util.EnumSet.copyOf() method is used to create an enum set with the same element type as the specified enum set, initially containing the same elements (if any).

Syntax

public static <E extends Enum<E>> EnumSet<E> copyOf(EnumSet<E> s)

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

Parameters

s Specify the enum set from which to initialize this enum set.

Return Value

Returns a copy of the specified enum set.

Exception

Throws NullPointerException, if s is null.

Example:

In the example below, the java.util.EnumSet.copyOf() method is used to create an enum set with the same element type as the specified enum set.

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) {
    //create EnumSets
    EnumSet<weekday> Set1;
    EnumSet<weekday> Set2;

    //populating Set1
    Set1 = EnumSet.of(weekday.MON, weekday.TUE, weekday.WED);

    //print the Set1
    System.out.println("Set1 contains: "+ Set1); 

    //initializing Set2 using Set1 and copyof() method
    Set2 = EnumSet.copyOf(Set1);
    
    //print the content of Set2
    System.out.println("Set2 contains: "+ Set2); 
  }
}

The output of the above code will be:

Set1 contains: [MON, TUE, WED]
Set2 contains: [MON, TUE, WED]

❮ Java.util - EnumSet