Java Utility Library

Java EnumSet - copyOf() Method



The java.util.EnumSet.copyOf() method is used to create an enum set initialized from the specified collection.

Syntax

public static <E extends Enum<E>> EnumSet<E> copyOf(Collection<E> c)

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

Parameters

c Specify the collection from which to initialize this enum set.

Return Value

Returns an enum set initialized from the given collection.

Exception

  • Throws NullPointerException, if c is null.
  • Throws IllegalArgumentException, if c is not an EnumSet instance and contains no elements.

Example:

In the example below, the java.util.EnumSet.copyOf() method is used to create an enum set initialized from the specified collection.

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 a collection
    Collection<weekday> col = new ArrayList<weekday>();

    //populating the collection
    col.add(weekday.SUN);
    col.add(weekday.SAT);

    //print the collection
    System.out.println("Collection contains: "+ col); 

    //creating EnumSet and initializing 
    //it with collection
    EnumSet<weekday> Set;
    Set = EnumSet.copyOf(col);
    
    //print the content of Set
    System.out.println("Set contains: "+ Set); 
  }
}

The output of the above code will be:

Collection contains: [SUN, SAT]
Set contains: [SUN, SAT]

❮ Java.util - EnumSet