The LinkedHashSet is ordered by insertion order. In cases where you are getting things in order (say from a query in a database) this maintains the order you get them and provides you with O(1) lookup into that (compared with the O(log n) for a TreeSet). Its also useful for when the ordering of the objects isn't something that is easily comparable.
The LinkedHashSet is also particularly useful for caches (see also its kin the LinkedHashMap which provides a method for removeEldestEntry
which can be used to implement an LRU cache (evicting objects to maintain only the 100 (or whatever its configured for) most recently used items).
However, the LinkedHashSet is not a subclass of the interface NavigableSet. This means that a number of tools for manipulating the set are not there. To reverse the NavigableSet, you can get the descendingIterator()
or descendingSet()
. There are other bits in there like being able to get the next highest value of something, or the subset from one point to another.
There are two classes that implement the NavigableSet: ConcurrentSkipListSet (which uses a skip list) and TreeSet (which uses a red black tree).
The requirement for a NavigableSet is that the elements have an ordering to them (as implemented by Comparable
. These include String, Date, as well as various number classes, and a whole bunch more... or for that matter, anything that you implement Comparable.
Note that these are all sets which means that there is only one copy of an element in the structure. If you are actually after a List with multiple copies, then you've got your Lists to work from. These are different tools for different purposes.