Earlier
we have discussed HashSet, LinkedHashSet class. In this tutorial we will learn
about TreeSet class.
TreeSet Class:-
-
Contains only unique elements.
-
TreeSet implements the NavigableSet interface.
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