CKTIS / Java
EnumSet — a set of constants from one enum type
EnumSet stores constants of one enum type without duplicates. Learn to create sets with of and allOf and use the add, remove, and contains operations.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
EnumSet<E> selected = EnumSet.of(E.VALUE);
EnumSet<E> all = EnumSet.allOf(E.class);
boolean added = selected.add(E.OTHER);
boolean removed = selected.remove(E.VALUE);
boolean present = selected.contains(E.OTHER);java.util.EnumSet<E> is a mutable set of constants from one enum type, internally represented by bit vectors. Iteration follows constant declaration order, not insertion order.
EnumSet.of(...) creates a set of selected constants; it requires at least one. EnumSet.allOf(E.class) creates a set containing every constant of the type. Create an empty set with EnumSet.noneOf(E.class).
EnumSet.add adds an absent element, and EnumSet.remove removes a present element; both return true only when they change the set. Adding an element again does not create a duplicate. EnumSet.contains returns true if the element belongs to the set; it does not modify the contents.
Adding null throws NullPointerException; contains(null) and remove(null) return false. The set is not synchronized: shared access involving modification requires external synchronization. The example targets Java SE 21; it does not attest to the production runtime version.
Examples
import java.util.EnumSet;
public class Main {
enum Permission { READ, WRITE, EXECUTE }
public static void main(String[] args) {
EnumSet<Permission> selected =
EnumSet.of(Permission.WRITE, Permission.READ);
System.out.println(selected);
System.out.println(selected.add(Permission.EXECUTE));
System.out.println(selected.add(Permission.READ));
System.out.println(selected.remove(Permission.WRITE));
System.out.println(selected.contains(Permission.WRITE));
System.out.println(selected);
System.out.println(EnumSet.allOf(Permission.class));
}
}Result
[READ, WRITE] true false true false [READ, EXECUTE] [READ, WRITE, EXECUTE]
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.