tags:

views:

626

answers:

3

I want to do something like this:

public enum Permissions
{
    CanBlah1,
    CanBlah2,
    CanBlah3
}

byte[] userPerm = Permissions.CanBlah1 | Permissions.CanBlah2;

// check permssions
//
if(userPerm && Permissions.CanBlah1 == Permissions.CanBlah1)
{
      // do something
}

Can you do this in Java like that? (I'm coming from a c# background)

A: 

As far as I know bitwise operator is undefined for enum types

Upul
Yes, but `EnumSet` has the essential set operations, e.g. union via `addAll()` and intersection via `retainAll()`. See also: http://en.wikipedia.org/wiki/Set_(mathematics)
trashgod
+5  A: 

You can easily do it using EnumSet

import java.util.EnumSet;

import static java.util.EnumSet.of;
import static java.util.EnumSet.range;
import static so.User.Permissions.CanBlah1;
import static so.User.Permissions.CanBlah2;
import static so.User.Permissions.CanBlah3;

public class User {
    public enum Permissions {
        CanBlah1,
        CanBlah2,
        CanBlah3
    }

    public static void main(String[] args) throws Exception {
        EnumSet<Permissions> userPerms = of(CanBlah1, CanBlah2);
        System.out.println(userPerms.contains(CanBlah1)); //true
        System.out.println(userPerms.contains(CanBlah2)); //true
        System.out.println(userPerms.contains(CanBlah3)); //false
        System.out.println(userPerms.containsAll(of(CanBlah1, CanBlah3))); //false
        System.out.println(userPerms.containsAll(range(CanBlah1, CanBlah2))); //true
        System.out.println(userPerms.containsAll(range(CanBlah1, CanBlah3))); //false
    }

}
Chandra Patni
And, of course, EnumSet is implemented as a bitmask under the hood.
Ross
They are. It uses `long` for upto 64 `Enums` byte arrays, so called `JubmoSet`.
Chandra Patni
A: 

While i wouldn't recommend it, you can ask for the ordinal() of an enum and use that for bit operations. Of course since you can't define what the ordinal is for an enum, you have to insert bogus values to get the ordinals right

enum Example {
   Bogus,            --> 0
   This,             --> 1
   That,             --> 2
   ThisOrThat        --> 3
};

Notice a Bogus enum needed to be introduced so that

ThisOrThat.ordinal() == This.ordinal() | That.ordinal()
MeBigFatGuy