Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

EnumSet

A set of values of one enum. Works like a set of bit flags, but with readable code.

Available since: Java 5

Syntax

public abstract class EnumSet<E extends Enum<E>> extends AbstractSet<E>

Examples

Creating sets with factory methods:

enum Day { MON, TUE, WED, THU, FRI, SAT, SUN }
 
void main() {
    EnumSet<Day> weekend = EnumSet.of(Day.SAT, Day.SUN);
    EnumSet<Day> workdays = EnumSet.complementOf(weekend);
 
    IO.println(weekend);
    IO.println(workdays);
    IO.println(EnumSet.range(Day.TUE, Day.THU));
    IO.println(workdays.contains(Day.FRI));
}

Output:

[SAT, SUN]
[MON, TUE, WED, THU, FRI]
[TUE, WED, THU]
true

Permissions as a set of flags:

enum Permission { READ, WRITE, DELETE }
 
void main() {
    EnumSet<Permission> perms = EnumSet.noneOf(Permission.class);
    perms.add(Permission.READ);
    perms.add(Permission.WRITE);
 
    IO.println(perms);
    IO.println(perms.containsAll(EnumSet.of(Permission.READ, Permission.DELETE)));
    IO.println(EnumSet.allOf(Permission.class));
}

Output:

[READ, WRITE]
false
[READ, WRITE, DELETE]

Notes

You create it with of(), noneOf(), allOf(), range(), complementOf(), copyOf() rather than new. Inside is a long where each bit stands for one constant, so the operations are very fast. Elements are always iterated in declaration order. The set is mutable; for an unmodifiable one use Set.copyOf(enumSet) or Collections.unmodifiableSet().

See also

  • EnumMap — A map whose keys are values of one enum. Fast, and keeps keys in declaration order.
  • Enum.values() — Methods of every enum: values() gives all constants, valueOf() finds one by name, ordinal() and name() give its index and name.
  • HashSet — A set without duplicates backed by a hash table; order is not guaranteed.
  • & | ^ ~ << >> >>> — Bitwise operators work with individual bits of integers: AND, OR, XOR, NOT and shifts.

Related recipes

In the tutorial

  • Collections for enums — EnumMap and EnumSet in Java: a map and a set for enum constants, ranges and complements, values(), valueOf() and why you should not rely on ordinal().

Thanks for reading!

Donate to the site — we work hard for you.