In this tutorial, we will learn about the Java EnumSet class and its various methods with the help of examples.
The EnumSet class of the Java collections framework provides a set implementation of elements of a single enum.
EnumSet class which is implemented in the collections framework is one of the specialized implementation of Set interface for use with the enumeration type. It is a high performance set implementation, much faster than HashSet. All of the elements in an enum set must come from a single enumeration type that is specified when the set is created either explicitly or implicitly. Lets see how to create a set object using this class.
// Java program to demonstrate the
// creation of the set object
// using the EnumSet class
import java.util.*;
enum Code {
CODE,
LEARN,
CONTRIBUTE,
QUIZ,
MCQ
}
;
public class Codemistic {
public static void main(String[] args)
{
// Creating a set
Set<Code> set1;
// Adding the elements
set1 = EnumSet.of(Code.QUIZ,
Code.CONTRIBUTE,
Code.LEARN,
Code.CODE);
System.out.println("Set 1: " + set1);
}
}
output:
Set 1: [CODE, LEARN, CONTRIBUTE, QUIZ]
Method | Description |
---|---|
static <E extends Enum<E>> EnumSet<E> allOf(Class<E> elementType) | It is used to create an enum set containing all of the elements in the specified element type. |
static <E extends Enum<E>> EnumSet<E> copyOf(Collection<E> c) | It is used to create an enum set initialized from the specified collection. |
static <E extends Enum<E>> EnumSet<E> noneOf(Class<E> elementType) | It is used to create an empty enum set with the specified element type. |
static <E extends Enum<E>> EnumSet<E> of(E e) | It is used to create an enum set initially containing the specified element. |
static <E extends Enum<E>> EnumSet<E> range(E from, E to) | It is used to create an enum set initially containing the specified elements. |
EnumSet<E> clone() | It is used to return a copy of this set. |