I looked under the hood for EnumSet.allOf
and it looks very efficient, especially for enums with less than 64 values.
Basically all sets share the singl
EnumSet
is not built with the intention to iterate over it's values. Rather it is implemented with the idea for it to represent a BitMap or BitMask efficiently (or reasonably efficient). The javadoc on EnumSet also states:
Enum sets are represented internally as bit vectors. This representation is extremely compact and efficient. The space and time performance of this class should be good enough to allow its use as a high-quality, typesafe alternative to traditional int-based "bit flags." Even bulk operations (such as containsAll and retainAll) should run very quickly if their argument is also an enum set.
Because only one single bit can represent a certain Enum value, it is also implemented as a Set
and not as a List
.
Now, it is probably also true that you can accomplish the same, and faster, using C-style bit masks (x^2), however it offers a more intuitive coding style and type safe use using enums, and it expands easily beyond the size of what an int
or long
can contain.
As such you can test that all bits are set as follows:
public class App {
enum T {A,B}
public static void main(String [] args) {
EnumSet t = EnumSet.of(T.A);
t.containsAll(EnumSet.allOf(T.class));
}
}