Java Collections - Set

Implementations of Set

Java provides several implementations of the Set Interface - each tailored for a particular design requirement.

CopyOnWriteArraySet

As the name suggests, this class implements the Set interface. Any write to this set triggers a new copy of the entire set. Although this sounds crazy, it is extremely useful when there is a heavy load of concurrent reads and very few writes onto a small data set. In such a scenario, the concurrrent reads can continue without any block. You can be certain that its iterator will never through a ConcurrentModificationException. Ofcourse it is Thread Safe. But you should note that any mutative operations are expensive.

EnumSet

This class is used specially for working with elements of an enum. The iterator returned by the iterator method traverses the elements in their natural order (the order in which the enum constants are declared). It is Thread Safe The returned iterator is weakly consistent: it will never throw ConcurrentModificationException and it may or may not show the effects of any modifications to the set that occur while the iteration is in progress.

HashSet

This class provides one of the most commonly used set implementations. It is Not Thread Safe. There are no guarantees about how it will behave on concurrent access. Its fail-fast behavior is not guaranteed. It provides constant time performance for access for all elements - because it uses the hash function for accessing the elements rather than comparing each element. It is based on a HashMap.

LinkedHashSet

This class is similar to the HashSet. Except that it maintains a doubly-linked list running through all of its entries. It is Not Thread Safe. Its fail-fast behavior is not guaranteed.

TreeSet

This class provides guaranteed log(n) time cost for the basic operations. It is Not Thread Safe. There are no guarantees about how it will behave on concurrent access. Its fail-fast behavior is not guaranteed. It is based on a TreeMap. The iterator returns elements based on their natural ordering (or as per the Comparator). It implements the NavigableSet interface based on a TreeMap.

ConcurrentSkipListSet

A scalable concurrent NavigableSet implementation based on a ConcurrentSkipListMap. This implementation provides expected average log(n) time cost for access. It is Thread Safe The returned iterator is weakly consistent. The access to elements is atomic. But bulk access such as size, addAll, removeAll, retainAll, containsAll, equals, and toArray is not guaranteed to be atomic.