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 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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With