Описание тега treeset
TreeSet implements interface NavigableSet which is a sub-interface of SortedSet. So in addition to being a Set - i.e. a Collection containing unique entries - a TreeSet sorts its entries either by their natural order if they are Comparable or by an explicit Comparator provided as a constructor parameter.
The class name originates in the fact that a TreeSet is backed by a TreeMap which in turn implements a red-black tree (a self-balancing binary search tree) to order its elements.
Please note that elements are implicitly assumed to be immutable, i.e. their order is never updated after insertion. This makes updating entries in a TreeSet tricky, because it only works in this specific order:
- Remove element from TreeSet
- Modify element properties
- Re-add element to TreeSet
Refrain from modifying entries before removal, because a modified entry might not even be found in the set anymore after modification.
Please also note that this kind of remove or update operation should never be done while iterating over the set because it would lead to undefined Iterator behaviour. So you either need to iterate over a copy of the set or use an advanced 3rd party implementation like the UpdateableTreeSet provided by Alexander Kriegisch.