A TreeSet can be termed as a NavigableSet implementation based on a TreeMap, wherein the elements are ordered using their natural ordering or by a Comparator provided during creation, based on the constructor that is used.
- TreeSet implements the SortedSet interface so duplicate values are not allowed.
- Objects in a TreeSet are stored in a sorted and ascending order.
- TreeSet does not preserve the insertion order of elements but elements are sorted by keys.
- TreeSet does not allow to insert Heterogeneous objects. It will throw ClassCastException at Runtime if trying to add heterogeneous objects.
- TreeSet serves as an excellent choice for storing large amounts of sorted information which are supposed to be accessed quickly because of its faster access and retrieval time.
- TreeSet is basically implementation of a self-balancing binary search tree like Red-Black Tree. Therefore operations like add, remove and search take O(Log n) time.
- Operations like printing n elements in sorted order takes O(n) time.
Constructors in TreeSet:
- TreeSet() This is default constructor for Treeset.
- TreeSet(Comparator comp) This constructor is used for custom specific object sorting.
- TreeSet(Collection col) This constructor is used when any conversion is needed from any Collection object to TreeSet object.
- TreeSet(SortedSet s) This constructor is used to convert Set object to TreeSet Object.
Example:
Output:
true
true
[22,23]