EnumSet in Java

In this tutorial, we are going to discuss the basic concepts of EnumSet in Java.

First of all, EnumSet is a special set implementation of enum types.
The EnumSet implements a set interface and extends the Collection interface.

Points to Remember

  • EnumSet contains only enumeration values belonging to the same enumeration type.
  • Java EnumSet is a member of the Java collection Framework.

Declaration of Enumset

We should declare the Java EnumSet as follows.

public abstract class EnumSet<E extends Enum<E>>

Let us see some methods in an EnumSet.

1. allOf method

The allOf method generally used to create an enumeration set. that contains all of the elements declared in the element type.
Syntax of allOf method: static<E extends Enum <E>>EnumSet <E> allOf(Class<E>elementType)

2.copyOf method in EnumSet

The copyOf method generally used to create an enumeration set from the given collection.

Here is the declaration of copyOf method:

static<E extends Enum<E>> EnumSet<E> copyOf(Collection<E> a)

3. noneOf method in EnumSet

The noneOf method generally used to create an empty enumeration set.
Here is the declaration of noneOf method:

static <E extends Enum<E>>EnumSet<E> noneOf(Class <E> element)

4. The range method of Java EnumSet

The range method particularly used to create an enumeration set initially containing the specified elements.

Syntax:

static <E extends Enum<E>> EnumSet<E> range(E from, E to)

5. clone method.

The clone method generally used to return a copy of the set.

Syntax:

EnumSet<E> clone().

Finally, we will see a program to implement EnumSet.

Java code to implement EnumSet.

Here, is the Java code to implement EnumSet.

import java.util.*;  
enum program {  
  C,CPP, JAVA, PYTHON, C#, RUBY;  
}  
public class EnumSetProgram {  
  public static void main(String[] args) {  
    Set<program> set = EnumSet.of(program.JAVA, program.PYTHON);  
 
    Iterator<program> itrn = set.iterator();  
    while (itrn.hasNext())  
      System.out.println(itrn.next());  
  }  
}

The above program prints the following output.

JAVA
PYTHON

 

Leave a Reply

Your email address will not be published. Required fields are marked *