Summary

This lesson lists the important interfaces and classes of the Collections Framework.

We'll cover the following...

Set

EnumSet

An EnumSet is a specialized Set collection to work with enum classes. EnumSet should always be preferred over any other Set implementation when we are storing enum values. All of the elements in an enum set must come from a single enum type that is specified, explicitly or implicitly, when the set is created. Enum sets are represented internally as bit vectors.

EnumSet is a public abstract class that contains multiple static factory methods that allow us to create instances. There are two implementations:

  • RegularEnumSet: RegularEnumSet uses a single long to represent the bit vector. Each bit of the long element represents a value of the enum. The i-th value of the enum will be stored in the i-th bit, so it’s quite easy to know whether a value is present or not. Since long is a 64-bit data type, this implementation can store up to 64 elements.

  • JumboEnumSet: JumboEnumSet uses an array of long elements as a bit vector. This lets this implementation store more than 64 elements. It works pretty much like the RegularEnumSet but making some extra calculations to find the array index where the value is stored. Unsurprisingly, the first long element of the array will store the 64 first values of the enum, the second element the next 64, and so on.

Example

 EnumSet<DayOfWeek> myEnumSet = EnumSet.allOf(DayOfWeek.class);
 System.out.println(myEnumSet.contains(DayOfWeek.MONDAY));

HashSet

This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element.

LinkedHashSet

Hash table and linked list implementation of the Set interface, with predictable iteration order. This implementation differs from HashSet in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (insertion-order). Note that insertion order is not affected if an element is re-inserted into the set.

CopyOnWriteArraySet

A Set that uses an internal CopyOnWriteArrayList for all of its operations.

  • It is thread-safe.

  • It is best suited for applications in which set sizes generally stay small, read-only operations vastly outnumber mutative operations, and you need to ...