Java Enumset

The EnumSet class in Java is designed specifically for working with enum types as a specialized implementation of the Set interface. It extends the AbstractSet class.

EnumSet class hierarchy

The diagram below illustrates the hierarchy of the EnumSet class.

EnumSet class declaration

Let's examine the declaration of the java.util.EnumSet class.

Example

public abstract class EnumSet<E extends Enum<E>> extends AbstractSet<E> implements Cloneable, Serializable

Methods of Java EnumSet class

Method Description
static static <span> EnumSet</span> allOf(Class<code> elementType) It is used to create an enum set containing all of the elements in the specified element type. > EnumSetEnumSet allOf(ClassClass elementType) It is used to create an enum set containing all of the elements in the specified element type.
static static <span> EnumSet</span> copyOf(Collection<? extends E> c) It is used to create an enum set initialized from the specified collection. > EnumSetEnumSet copyOf(CollectionCollection<E> c) It is used to create an enum set initialized from the specified collection.
static <span> EnumSet</span>> EnumSetEnumSet noneOf(ClassClass elementType) It is used to create an empty enum set with the specified element type.
static <span> EnumSet</span>> EnumSet<span> EnumSet</span> of(E e) It is used to create an enum set initially containing the specified element.
static <span> EnumSet</span>> EnumSetEnumSet 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.

Java EnumSet Example

Example

import java.util.*;

enum days {

  SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY

}

public class Main {

  public static void main(String[] args) {

    Set<days> set = EnumSet.of(days.TUESDAY, days.WEDNESDAY);

    // Traversing elements

    Iterator<days> iter = set.iterator();

    while (iter.hasNext())

      System.out.println(iter.next());

  }

}

Output:

Output

TUESDAY

WEDNESDAY

Java EnumSet Example: allOf and noneOf

Example

import java.util.*;

enum days {

  SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY

}

public class Main {

  public static void main(String[] args) {

    Set<days> set1 = EnumSet.allOf(days.class);

      System.out.println("Week Days:"+set1);

      Set<days> set2 = EnumSet.noneOf(days.class);

      System.out.println("Week Days:"+set2);   

  }

}

Output:

Output

Week Days:[SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY]

Week Days:[]

Input Required

This code uses input(). Please provide values below: