Google News
logo
Java Treeset
TreeSet
1. The underlying data Structure is BalencedTree.
2. Insertion order is not preserved it is based some sorting order.
3. Hetrogeneous data is not allowed.
4. Duplicate objects are not allowed
5. Null insertion is possible only once.
Constructors of Java TreeSet class
TreeSet set=newTreeSet()
It is used to construct an empty tree set that will be sorted in an ascending order according to the natural order of the tree set.
TreeSet set=new TreeSet(Collection c)
It is used to build a new tree set that contains the elements of the collection c.
TreeSet set=new TreeSet(Comparator comp)
It is used to construct an empty tree set that will be sorted according to given comparator.
TreeSet set=new TreeSet(SortedSet ss)
It is used to build a TreeSet that contains the elements of the given SortedSet.
TreeSet program
import java.util.*; 
class Test 
{ 
public static void main(String[] args) 
{ 
TreeSet t=new TreeSet(); 
t.add(50); 
t.add(20); 
t.add(40); 
t.add(10); 
t.add(30); 
System.out.println(t); 
SortedSet s1=t.headSet(50); 
System.out.println(s1);
SortedSet s2=t.tailSet(30); 
System.out.println(s2);
SortedSet s3=t.subSet(20,50); 
System.out.println(s3);
}
}
Output :
[10,20,30,40]
[30,40,50]
[20,30,40]