Justification for using a bitfield instead of EnumSet in modern Java 8 API

风流意气都作罢 提交于 2019-11-27 12:57:34

问题


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?


回答1:


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).




回答2:


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.



来源:https://stackoverflow.com/questions/22596495/justification-for-using-a-bitfield-instead-of-enumset-in-modern-java-8-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!