Card image cap

Exploring Java Collections - Understanding TreeSets

Java Concepts  • Posted one year ago

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.

  1. TreeSet implements the SortedSet interface so duplicate values are not allowed.
  2. Objects in a TreeSet are stored in a sorted and ascending order.
  3. TreeSet does not preserve the insertion order of elements but elements are sorted by keys.
  4. TreeSet does not allow to insert Heterogeneous objects. It will throw ClassCastException at Runtime if trying to add heterogeneous objects.
  5. 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.
  6. 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.
  7. 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:

data/Admin/treeset.png

Output:

true
true
[22,23]
We use cookies to provide you with a great user experience, analyze traffic and serve targeted promotions.   Learn More   Accept