views:

116

answers:

3

I want to store permissions in a bit set to compare them efficiently in Java. A 1 would mean permission granted and 0 permission denied. If the authorization is performed the required permissions would be compared to the permission set.

My idea is to use AND and compare the result with the requested permissions.

Example:

     0010 1101 Granted Permissions
AND  0000 0101 Requested Permissions
=    0000 0101 Result

if (Result == Requested Permissions)
    allow
else
    deny

Could that be done more efficient or simple?

+3  A: 

I'll focus on the "simple" part, because I don't think that this operation will be a performance bottleneck in any serious application.

You can use a BitSet which has all the necessary operations.

A more OO-approach and much easier to understand and read would be to represent your permissions with an enum and to use a EnumSet. For enums with only a few values it will be about as performant as the BitSet, because it'll use a very similar implementation.

Joachim Sauer
I'd prefer EnumSet, but the corresponding enum had to be present at compile time of my library. But the user of the library should be able to define its own permissions.
deamon
In that case you can still use a BitSet.
Joachim Sauer
+2  A: 

If you are using Java 5 or later, I recommend using Enum(s) and an EnumSet instead. It is much easier to handle and AFAIK performs equally well.

Péter Török
A: 

Your approach is perfectly fine and will work as expected. Sure, you could do this in several more complicated ways but I see nothing wrong in using bit manipulation operators if the context fits as it does in your case. After all these operators are part of the Java core language and are not marked as @deprecated or @evil.

x4u