Curriculum
In Java, EnumSet is a specialized Set implementation that is designed for use with enums. EnumSet stores a set of enum constants in a compact, efficient manner, which makes it more efficient than other Set implementations.
Here’s an example of how to use EnumSet in Java:
import java.util.EnumSet; enum Days { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY } public class EnumSetExample { public static void main(String[] args) { // create an EnumSet of Days EnumSet<Days> weekdays = EnumSet.of(Days.MONDAY, Days.TUESDAY, Days.WEDNESDAY, Days.THURSDAY, Days.FRIDAY); // print the EnumSet System.out.println("Weekdays: " + weekdays); // add an element to the EnumSet weekdays.add(Days.SATURDAY); // print the EnumSet after adding an element System.out.println("Weekdays after adding SATURDAY: " + weekdays); // remove an element from the EnumSet weekdays.remove(Days.MONDAY); // print the EnumSet after removing an element System.out.println("Weekdays after removing MONDAY: " + weekdays); } }
Output:
Weekdays: [MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY] Weekdays after adding SATURDAY: [MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY] Weekdays after removing MONDAY: [TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY]
Here are some of the commonly used methods of EnumSet:
of(E e, E... others)
: Creates an EnumSet with the specified elements.range(E from, E to)
: Creates an EnumSet with all of the elements in the range from from
to to
.allOf(Class<E> elementType)
: Creates an EnumSet with all of the elements of the specified enum type.noneOf(Class<E> elementType)
: Creates an empty EnumSet with the specified enum type.add(E e)
: Adds the specified element to the set.remove(Object o)
: Removes the specified element from the set.contains(Object o)
: Returns true if the set contains the specified element.size()
: Returns the number of elements in the set.isEmpty()
: Returns true if the set contains no elements.clear()
: Removes all of the elements from the set.iterator()
: Returns an iterator over the elements in the set.clone()
: Returns a shallow copy of the set.In addition to these methods, EnumSet also provides methods that are specific to enums. These methods include:
complementOf(EnumSet<E> s)
: Returns an EnumSet containing all of the elements in the specified EnumSet that are not in this EnumSet.copyOf(Collection<E> c)
: Creates an EnumSet containing all of the elements in the specified collection.copyOf(EnumSet<E> s)
: Creates an EnumSet containing all of the elements in the specified EnumSet.of(E first, E second)
: Creates an EnumSet containing the two specified elements.of(E first, E second, E... rest)
: Creates an EnumSet containing the specified elements.EnumSet provides many benefits over other Set implementations when working with enums, such as increased performance and type safety. Additionally, since enums are constants and cannot be changed at runtime, EnumSet is also immutable and thread-safe.