欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Item 32: Use EnumSet instead of bit fields

程序员文章站 2022-05-18 14:38:06
...

1.  The java.util package provides the EnumSet class to efficiently represent sets of values drawn from a single enum type. This class implements the Set interface, providing all of the richness, type safety, and interoperability you get with any other Set implementation. But internally, each EnumSet is represented as a bit vector. If the underlying enum type has sixty-four or fewer elements, the entire EnumSet is represented with a single long, so its performance is comparable to that of a bit field. Bulk operations, such as removeAll and retainAll, are implemented using bitwise arithmetic, just as you’d do manually for bit fields.

 

2.  EnumSet provides a rich set of static factories for easy set creation.

 

3.  The one real disadvantage of EnumSet is that it is not, as of release 1.6, possible to create an immutable EnumSet.