Java EnumSet Real-Time Example

In this source code example, you will learn how to use the Java EnumSet class in real-time Java projects.

Real-World Use Case: Managing User Permissions with EnumSet

import java.util.EnumSet;

// Define an enumeration for permissions
enum Permission {
    READ, WRITE, EXECUTE, DELETE
}

class User {
    private String name;
    private EnumSet<Permission> permissions;

    public User(String name, EnumSet<Permission> permissions) {
        this.name = name;
        this.permissions = permissions;
    }

    public boolean hasPermission(Permission permission) {
        return permissions.contains(permission);
    }

    @Override
    public String toString() {
        return name + " has permissions: " + permissions;
    }
}

public class PermissionManager {
    public static void main(String[] args) {
        // 1. Granting all permissions
        User admin = new User("Admin", EnumSet.allOf(Permission.class));
        System.out.println(admin);

        // 2. Granting read-only permission
        User guest = new User("Guest", EnumSet.of(Permission.READ));
        System.out.println(guest);

        // 3. Checking user permissions
        System.out.println("Admin has WRITE permission: " + admin.hasPermission(Permission.WRITE));
        System.out.println("Guest has WRITE permission: " + guest.hasPermission(Permission.WRITE));
    }
}

Output:

Admin has permissions: [READ, WRITE, EXECUTE, DELETE]
Guest has permissions: [READ]
Admin has WRITE permission: true
Guest has WRITE permission: false

Explanation:

1. The Permission enum lists the different types of permissions a user can have. Using EnumSet, we can efficiently represent a combination of these permissions.

2. The User class uses an EnumSet to store the permissions granted to the user. The hasPermission method checks if a specific permission is present in the user's EnumSet of permissions.

3. In the PermissionManager class:

- An admin user is granted all permissions using EnumSet.allOf(Permission.class).

- A guest user is granted only the read permission using EnumSet.of(Permission.READ).

- We then check and print whether each user has the WRITE permission.


Comments