Look again at the documentation for TreeSet. Look especially at the constructors. In the last lab we used the no-argument constructor and, if you read the documentation, our TreeSet will store the data according to the natural ordering of the data. In the case of Integer and String, the natural orders are increasing numerically and increasing alphabetically. We just went to a lot of trouble to define new classes DescendingInt and DescendingString that had the opposite natural orders.
But there's another constructor that takes a Comparator.
Let's amend the code for Sort.java so that we can build a TreeSet using a different comparator. All we need to do is to supply a second constructor that allows us to pass in a Comparator. The code is in Sort.java. Study the new constructor. Look at the documentation and see what is a Comparator.
Did you notice that, unlike the case for most interfaces, there is a method mentioned that you do not need to provide? Go back to the documentation and figure out why you don't need to provide a equals(Object o) method.
You can construct an instance of the default comparator for Integer by using an anonymous inner class:
new Comparator leftAngleBrack Integer rightAngleBrack () { public int compare(Integer i, Integer j) { return ((i lessThan j) ? -1 : ((i == j) ? 0 : 1)); } }(Notice that you'll need to inserrt your own less-than and greater-than signs into the above.)
You can change the above into a comparator that gives the Integers the opposite natural order by changing just two numbers!
SortIntBack.java contains code that will instantiate a Sort object with a comparator so that commandline ints will be output in reverse order.
java SortIntBack 1 3 5 4 2 5 4 3 2 1
java SortStringBack one two three four five two three one four five