

Enum sets support iteration over ranges of enum types. Internally, it is represented by a bit-vector, typically a single long. All of the members of an enum set must be of the same enum type. There are two special-purpose Set implementations ĮnumSet is a high-performance Set implementation for enum types. LinkedHashSet has the same tuning parameters as HashSet, but iteration time is not affected by capacity. If your guess is way off, you may waste a bit of space, time, or both, but it's unlikely to be a big problem. If you accept the default load factor but want to specify an initial capacity, pick a number that's about twice the size to which you expect the set to grow. Otherwise, just accept the default it's almost always the right thing to do. If you care a lot about the space consumption of your HashSet, read the HashSet documentation for more information. The HashSet class has one other tuning parameter called the load factor.
Implement a set using basic data structures java code#
The following line of code allocates a HashSet whose initial capacity is 64. The initial capacity is specified by using the int constructor. Internally, the capacity is always rounded up to a power of two. In the past, there was some advantage to choosing a prime number as the initial capacity. If you don't specify an initial capacity, the default is 16. On the other hand, choosing an initial capacity that's too low wastes time by copying the data structure each time it's forced to increase its capacity. Thus, choosing an initial capacity that's too high can waste both space and time. One thing worth keeping in mind about HashSet is that iteration is linear in the sum of the number of entries and the number of buckets (the capacity). The LinkedHashSet implementation spares its clients from the unspecified, generally chaotic ordering provided by HashSet without incurring the increased cost associated with TreeSet. Implemented as a hash table with a linked list running through it, it provides insertion-ordered iteration (least recently inserted to most recently) and runs nearly as fast as HashSet. LinkedHashSet is in some sense intermediate between HashSet and TreeSet. It's a fair bet that you'll end up using HashSet most of the time. If you need to use the operations in the SortedSet interface, or if value-ordered iteration is required, use TreeSet otherwise, use HashSet. HashSet is much faster than TreeSet (constant-time versus log-time for most operations) but offers no ordering guarantees.

Which of these three to use is generally straightforward. The Set implementations are grouped into general-purpose and special-purpose implementations.
