Friday, June 8, 2018

TreeSet Class in Java with Example


Earlier we have discussed HashSetLinkedHashSet class. In this tutorial we will learn about TreeSet class.

TreeSet Class:-

- Contains only unique elements.
- TreeSet implements the NavigableSet interface.
- It maintains the ascending order of inserted elements.




Syntax:-

TreeSet <E> ts = new TreeSet <E>();

E: It is the generic type of individual object.


Sample Program of TreeSet:-

import java.util.TreeSet;

public class TreeSetDemo {
     
      public static void main(String[] args) {
           
           
            TreeSet <String> ts = new TreeSet <String>();
           
            ts.add("Ravi");
            ts.add("John");
            ts.add("Joe");
            ts.add("Elly");
            ts.add("John");
           
            System.out.println(ts);
           
      }

}


Output:
[Elly, Joe, John, Ravi]

Note:-  John is duplicate inserted but TreeSet always accept unique elements.

Synchronized TreeSet:-
In actual way, TreeSet is not synchronized but we make it synchronize by using Collections.synchronizedSet() method.

TreeSet ts = new TreeSet();
Set synts = Collections.synchronizedSet(ts);




               


No comments:

Post a Comment