Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

EnumSet: adding, checking, and removing permissions

Use `add`, `contains`, and `remove` to manage one enum-based permission set in Java SE 21. Iteration follows the order of the enum declarations, not the order of insertion.

Version: Java SE 21

Syntax

java.util.EnumSet<E>, where E extends Enum<E>
boolean add(E e)
boolean contains(Object o)
boolean remove(Object o)

java.util.EnumSet<E> is a mutable set of constants from one enum type. EnumSet.noneOf(Permission.class) creates an empty set for Permission constants. The operations grouped as EnumSet.add/contains/remove work on that same set: add and remove modify it in place and return true only when its contents change.

add(E e) inserts a missing constant. Adding it again returns false and creates no duplicate. contains(Object o) returns true if the element is present, without changing the set. remove(Object o) deletes a present element and returns false if it was already absent.

add takes an element of type E, whereas contains and remove take Object. That does not mean a string name is converted to an enum constant: "WRITE" does not match Permission.WRITE. add(null) throws NullPointerException; contains(null) and remove(null) return false.

The iterator visits only the constants currently in the set, in the order they were declared in the enum. If READ is declared before WRITE, the loop visits READ first even if WRITE was added first.

Examples

import java.util.EnumSet;

public class EnumSetPermissions {
    enum Permission { READ, WRITE }

    public static void main(String[] args) {
        EnumSet<Permission> permissions = EnumSet.noneOf(Permission.class);

        System.out.println("add WRITE: " + permissions.add(Permission.WRITE));
        System.out.println("add READ: " + permissions.add(Permission.READ));
        System.out.println("add WRITE again: " + permissions.add(Permission.WRITE));
        System.out.println("contains WRITE: " + permissions.contains(Permission.WRITE));

        for (Permission permission : permissions) {
            System.out.println("iterate: " + permission.name());
        }

        System.out.println("remove WRITE: " + permissions.remove(Permission.WRITE));
        System.out.println("remove WRITE again: " + permissions.remove(Permission.WRITE));
        System.out.println("contains WRITE: " + permissions.contains(Permission.WRITE));
    }
}

Result

add WRITE: true
add READ: true
add WRITE again: false
contains WRITE: true
iterate: READ
iterate: WRITE
remove WRITE: true
remove WRITE again: false
contains WRITE: false

`WRITE` is added first, but the loop prints `READ` before `WRITE`. The first removal of `WRITE` returns `true`, the second returns `false`, and the final membership check also returns `false`.

Related lessons

  • Java · Lesson 19 · Advanced · Version: 2

Sources