|
This Class Implements Set Interface that uses Tree structure for the storage of the elements in the set. The objects in this are stored in the ascending order and the access to the elements in this type of arrangement is very quick and efficient and it gives us the feasibility to store a large number of data with this tree structure.
TreeSet has the following constructors:
TreeSet( ): This constructor create the default empty tree.
TreeSet(Collection c) : This builds a tree set that contains the elements of c.
TreeSet(Comparator comp): This constructor constructs an empty tree set that will be sorted according to the comparator specified by comp.
TreeSet(SortedSet ss): This constructor builds a tree set that contains the elements of ss.
import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;
public class TreeSetExample {
public static void main(String[] args) {
Set set = new TreeSet(new DescendingComparator());
set.add("1");
set.add("2");
set.add("3");
set.add("4");
set.add("3");
System.out.println(set);
}
}
class DescendingComparator implements Comparator {
public int compare(Object arg0, Object arg1) {
String str1 = (String) arg0;
String str2 = (String) arg1;
return -(str1.compareTo(str2));
}
}
|