Content deleted Content added
→Set interface implementations: Fix subheading issues |
→Set interface implementations: Add information for EnumSet |
||
Line 189:
Direct subclasses of {{java|AbstractSet}} include {{java|ConcurrentSkipListSet}}, {{java|CopyOnWriteArraySet}}, {{java|EnumSet}}, {{java|HashSet}} and {{java|TreeSet}}.
====EnumSet class====
The {{java|EnumSet}} class extends {{java|AbstractSet}}.
{{java|EnumSet}} is a good replacement for the ''bit fields'', which is a type of set, as described below.
Traditionally, whenever developers encountered elements of an enumerated type that needs to be placed in a set, the developer would use the ''int enum pattern'' in which every constant is assigned a different power of 2.{{sfn|Bloch|2018|loc=Chapter §5 Use EnumSet instead of bit fields|pp=169-170}} This bit representation enables the developer to use the bitwise OR operation, so that the constants can be combined into a set, also known as a ''bit field''.
This ''bit field representation'' enables the developer to make efficient set-based operations and bitwise arithmetic such as intersection and unions.{{sfn|Bloch|2018|loc=Chapter §5 Use EnumSet instead of bit fields|pp=169-170}}
However, there are many problems with ''bit field representation'' approach. A bit field is less readable than an int enum constant.{{sfn|Bloch|2018|loc=Chapter §5 Use EnumSet instead of bit fields|pp=169-170}} Also, if the elements are represented by bit fields, it is impossible to iterate through all
of these elements.{{sfn|Bloch|2018|loc=Chapter §5 Use EnumSet instead of bit fields|pp=169-170}}
A recommended alternative approach is to use an {{java|EnumSet}}, where an int enum is used instead of a ''bit field''.{{sfn|Bloch|2018|loc=Chapter §5 Use EnumSet instead of bit fields|pp=169-170}} This approach uses an {{java|EnumSet}} to represent the set of values that belong to the same {{java|Enum}} type.{{sfn|Bloch|2018|loc=Chapter §5 Use EnumSet instead of bit fields|pp=169-170}} Since the {{java|EnumSet}} implements the {{java|Set}} interface and no longer requires the use of bit-wise operations, this approach is more type-safe.{{sfn|Bloch|2018|loc=Chapter §5 Use EnumSet instead of bit fields|pp=169-170}} Furthermore, there are many static factories that allow for object instantiation, such as the method {{java|EnumSet.of()}} method.{{sfn|Bloch|2018|loc=Chapter §5 Use EnumSet instead of bit fields|pp=169-170}}
After the introduction of the {{java| EnumSet}}, the ''bit field representation'' approach is considered to be obsolete.{{sfn|Bloch|2018|loc=Chapter §5 Use EnumSet instead of bit fields|pp=169-170}}
====HashSet class====
|