Codectionary / Developer documentation / Java

EnumSet Membership

EnumSet stores members of one enum type compactly. It gives type-safe membership operations for feature selections or permissions. Save as Main.java and run with a Java 17+ JDK: java Main.java.

Syntax

EnumSet.of(EnumType.FIRST, EnumType.SECOND)

Examples

EnumSet Membership

Save as Main.java and run with a Java 17+ JDK: java Main.java.

import java.util.EnumSet;

public class Main {
  public static void main(String[] args) throws Exception {
    enum Feature { READ, WRITE, EXPORT }
    EnumSet<Feature> enabled = EnumSet.of(Feature.READ, Feature.WRITE);
    enabled.remove(Feature.WRITE);
    System.out.println(enabled.contains(Feature.READ));
    System.out.println(enabled);
  }
}
  1. Expected output: true [READ]
  2. Membership remains typed to Feature. Iteration follows enum declaration order, not insertion order.

Best practices

  • Use EnumSet.noneOf when starting with an empty set.
  • Copy mutable sets before exposing them to callers that should not change internal state.

Runtime & versions

Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Java Language Specification

Specifications & further reading