Close

Java Collections - EnumSet.copyOf() Examples

Java Collections Java Java API 


Class:

java.util.EnumSet

java.lang.Objectjava.lang.Objectjava.util.AbstractCollectionjava.util.AbstractCollectionjava.util.CollectionCollectionjava.util.AbstractSetjava.util.AbstractSetjava.util.SetSetjava.util.EnumSetjava.util.EnumSetjava.lang.CloneableCloneablejava.io.SerializableSerializableLogicBig

Methods:

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

Creates an enum set with the same element type as the specified enum set, initially containing the same elements (if any).



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

Creates an enum set initialized from the specified collection. If the specified collection is an EnumSet instance, this static factory method behaves identically to copyOf(EnumSet) . Otherwise, the specified collection must contain at least one element (in order to determine the new enum set's element type).


Examples


package com.logicbig.example.enumset;

import java.time.Month;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;

public class CopyOfExample {

public static void main(String... args) {
List<Month> monthList = new ArrayList<>();
monthList.add(Month.JANUARY);
EnumSet<Month> months = EnumSet.copyOf(monthList);
System.out.println(months);

//this will call the second overloaded version which actually clones the set
EnumSet<Month> months2 = EnumSet.copyOf(months);
System.out.println(months2);
}
}

Output

[JANUARY]
[JANUARY]




for copyOf(Collection) method, there has to be at least one element in the provided collection:

package com.logicbig.example.enumset;

import java.time.Month;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;

public class CopyOfExample2 {
public static void main(String... args) {
List<Month> list = new ArrayList<>();
EnumSet<Month> set = EnumSet.copyOf(list);
System.out.println(set);
}
}

Output

Caused by: java.lang.IllegalArgumentException: Collection is empty
at java.base/java.util.EnumSet.copyOf(EnumSet.java:174)
at com.logicbig.example.enumset.CopyOfExample2.main(CopyOfExample2.java:17)
... 6 more




See Also