TreeSet in Java

Price: INR 1,299.00
Was: INR 1,799.00

TreeSet in Java is the class in Java Collection Framework, Which implements the Set interface in Java.

 

Set In Java

A Set is a collection that contains unique records only. Set can’t contain the Duplicate Records. In provides three general purpose implementations in Java.

  • HashSet
  • LinkedHashSet
  • TreeSet

 

TreeSet in Java Collection

The TreeSet class is the simplest implementation of the Set interface. The TreeSet does not add any additional methods beyond those found in the Set interface. The TreeSet achieves good performance by using a hash to store the Object in the Set. The hash allows fast lookup.

Java HashSet does not guarantee any insertion orders but TreeSet auto sort the inserted elements, TreeSet stores the elements in a sorted manner.

 

Let’s understand the implementation of TreeSet with an easy example.

Output:

Values of HashSet is — [0, 10, 12, 25, 50]

 

In the above example, First we have declared the TreeSet named tSet, and then add some elements in the TreeSet.

Then we print the elements of the TreeSet, You noticed all elements are in sorted order. So treeSet insert the elements into sorted Order.

 

Difference in HashSet, LinkedHashSet, and TreeSet

All HashSet, LinkedHashSet, and TreeSet classes implement the single interface Set but there is some difference in these classes. Let’s understand these –

 

HashSet is Implemented using a hash table. Elements are not ordered. The add, remove and contains methods have constant time complexity O(1).

 

TreeSet is implemented using a tree structure(red-black tree in algorithm book). The elements in a TreeSet are sorted, but the add, remove and contains methods has the time complexity of O(log (n)). It offers several methods to deal with the ordered set like first(), last(), headSet(), tailSet(), etc.

 

LinkedHashSet is between HashSet and TreeSet. It stores the elements in the same order as they inserted.  It is implemented as a hash table with a linked list running through it, so it provides the order of insertion. The time complexity of basic methods is O(1).

 

Selenium Tutorial:

If you liked this video, then please subscribe to our YouTube Channel for more video tutorials.

0 Comment

Leave a Reply