Exploring Java Collections – Understanding TreeSets

Exploring Java Fundamentals - Understanding TreeSets

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:

wp-content/uploads/2022/05/treeset.png

Output:

true
true
[22,23]

Buy Me A Coffee

Found this article helpful? Please consider supporting!

Ram
Ram

I'm a full-stack developer and a software enthusiast who likes to play around with cloud and tech stack out of curiosity. You can connect with me on Medium, Twitter or LinkedIn.

Leave a Reply

Your email address will not be published. Required fields are marked *