The first two constructors create empty tree sets:
public TreeSet()
public TreeSet(Comparator comp)
Pass along a custom Comparator to the constructor that will be used to keep elements ordered.
Once the TreeSet is created, you cannot change the comparator.
import java.util.Collections;
import java.util.Set;
import java.util.TreeSet;
public class MainClass {
public static void main(String args[]) throws Exception {
String elements[] = { "A", "C", "D", "G", "F" };
Set set = new TreeSet(Collections.reverseOrder());
for (int i = 0, n = elements.length; i < n; i++) {
set.add(elements[i]);
}
System.out.println(set);
System.out.println(((TreeSet) set).comparator());
}
}
[G, F, D, C, A]
java.util.Collections$ReverseComparator@192d342