Collections - Set interface
Overview
A collection with no duplicate elements.Sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. As implied by its name, this interface models the mathematical set abstraction.
- The Set interface provides methods for accessing the elements of a finite mathematical set
- Sets do not allow duplicate elements
- Contains no methods other than those inherited from Collection
- It adds the restriction that duplicate elements are prohibited
- Two Set objects are equal if they contain the same elements
Main implementations of the Set interface are as follows:
TreeSet
- TreeSet is a Set implementation that keeps the elements in sorted order. The elements are sorted according to the natural order of elements or by the comparator provided at the time of creation.
- A NavigableSet implementation is based on a TreeMap. The elements are ordered using their natural ordering, or by a Comparator provided at set creation time, depending on which constructor is used.This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains).
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.
- A HashSet is an unsorted, unordered Set.
- It uses the hashcode of the object being inserted (so the more efficient your hashcode() implementation the better access performance you’ll get).
- Use this class when you want a collection with no duplicates and you don’t care about order when you iterate through it.
HashSet vs TreeSet
Operations | HashSet | TreeSet |
---|---|---|
Add/remove item | amort. O(1), worst O(n) | O(log n) |
Contains? | O(1) | O(log n) |
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).
EnumSet
! ! An EnumSet is a specialized set for use with enum types, all of the elements in the EnumSet type that is specified, ! ! explicitly or implicitly, when the set is created.
sorted set interface
A Set that further provides a total ordering on its elements. The elements are ordered using their natural ordering, or by a Comparator typically provided at sorted set creation time. The set’s iterator will traverse the set in ascending element order. Several additional operations are provided to take advantage of the ordering. (This interface is the set analogue of SortedMap.)