Java EnumSet Class



Introduction

The Java EnumSet class is a specialized Set implementation for use with enum types. Following are the important points about EnumSet −

  • All of the elements in an enum set must come from a single enum type that is specified, explicitly or implicitly, when the set is created.

  • Enum sets are represented internally as bit vectors.

  • EnumSet is not synchronized.If multiple threads access an enum set concurrently, and at least one of the threads modifies the set, it should be synchronized externally.

Class declaration

Following is the declaration for java.util.EnumSet class −

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

Class methods

Sr.No. Method & Description
1 static <E extends Enum<E>> EnumSet<E> allOf(Class<E> elementType)

This method creates an enum set containing all of the elements in the specified element type.

2 EnumSet<E> clone()

This method returns a copy of this set.

3 static <E extends Enum<E>> EnumSet<E> complementOf(EnumSet<E> s)

This method creates an enum set with the same element type as the specified enum set, initially containing all the elements of this type that are not contained in the specified set.

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

This method creates an enum set initialized from the specified collection.

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

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

6 static <E extends Enum<E>> EnumSet<E> noneOf(Class<E> elementType)

This method creates an empty enum set with the specified element type.

7 static <E extends Enum<E>> EnumSet<E> of(E e)

This method creates an enum set initially containing the specified element.

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

This method creates an enum set initially containing all of the elements in the range defined by the two specified endpoints.

Methods inherited

This class inherits methods from the following classes −

  • java.util.AbstractSet
  • java.util.AbstractCollection
  • java.util.Object
  • java.util.Set

Creating an EnumSet Example

The following example shows the usage of Java EnumSet of(E) method to populate the EnumSet instance. We've created a enum Numbers. Then a EnumSet instance is created using a enum value and resulted enumSet is printed.

package com.tutorialspoint;

import java.util.EnumSet;

public class EnumSetDemo {

   // create an enum
   public enum Numbers {
      ONE, TWO, THREE, FOUR, FIVE
   };

   public static void main(String[] args) {

      // create a set that contains an enum
      EnumSet<Numbers> set = EnumSet.of(Numbers.ONE);

      // print set
      System.out.println("Set:" + set);
   }
}

Let us compile and run the above program, this will produce the following result −

Set:[ONE]
Advertisements