tags:

views:

898

answers:

2

Is there a way in Java to declare an enumeration whose values can be used together? For example:

enum FileAccess { Read, Write, ReadWrite }

Is it possible to define ReadWrite as Read | Write (or anything that would yield the same result)?

+15  A: 

You use EnumSet:

EnumSet<FileAccess> readWrite = EnumSet.of(FileAccess.Read, FileAccess.Write);

This is actually somewhat more elegant than the C#/.NET way, IMO - aside from anything else, you can easily distinguish between a set and a single value.

Jon Skeet
Can you explain how you'd use this EnumSet to produce a read/write constant?
Paul Tomblin
Exactly in the way I've shown - just make it a final variable. EnumSet is immutable.
Jon Skeet
But that gives you a Set, not an Enum, or indeed an integer that you could store in a database (like Enum.ordinal()).
Paul Tomblin
If you want an external (DB) representation than bare enums are unacceptable -- using ordinals is a bad idea for maintainance reasons. After adding a external representation to your enums, add a wrapper around EnumSet to manage the combined external representation in both directions.
Darron
Thanks Darron, this summarizes what I was looking for.
Hosam Aly
+2  A: 

See EnumSet which allows you to do this efficiently:

EnumSet set = EnumSet.of(READ, WRITE);

JodaStephen