Question

EnumSet, as old as the enum itself (both since Java 5), is supposed to be a noncompromizing replacement for the use case of bitfields: as fast and lean as the bitfield (well, except for not being a primitive type), and typesafe to boot. On the other hand, the most recent and for years the most anticipated Java API—the Streams API—unashamedly employs bitfields for Spliterator's characteristics.

Should I consider the above as a clear admission by the core Java experts that EnumSet is not that good after all? Should I reconsider the common best-practice advice to never use bitfields?

Was it helpful?

Solution

Was rather suprised to see that it is using bitfields rather than EnumSet. The rational though is discussed in this mailing list thread. It seems like the reason was to be able to set and unset various characteristics without affecting the one on the caller end. With an EnumSet, to implement this, one would need to create a new EnumSet object every time there is a need to change it in different stages. I guess this is the reason why bit fields wins the race there.

The concluding sentence of that thread essentially anticipates your question here:

The presence of such flags in a Java 8 API would (and should) raise a lot of eyebrows, because it goes against what people have been told for well over a decade. If it's adopted as is, there had better be a good explanation for doc readers of why alternatives were rejected. "We were comfortable with int flags and nothing else significantly better suggested itself" won't cut it. "We know int flags aren't great for an API, but we tried very hard to find better alternatives, to no avail" would (if it were true).

OTHER TIPS

Should I reconsider the common best-practice advice to never use bitfields?

Yes. You should generally reconsider any advice that contains the words "always" or "never", no matter if it is "common" or not so common.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top