Example Natural Order and Total Order

import java.util.*;

public class ComparatorUsage {
    public static void main(String[] args) {

        // Choice of comparator.
    //  Set strSet = new TreeSet();                              // (1a)
    //  Set strSet = new TreeSet(String.CASE_INSENSITIVE_ORDER); // (1b)
        Set strSet = new TreeSet(new RhymingStringComparator()); // (1c)

        // Add each command line argument to the set.
        for (int i=0; i < args.length; i++) {                    // (2)
            strSet.add(args[i]);
        }
        System.out.println(strSet);                              // (3)
    }
}

class RhymingStringComparator implements Comparator {
    public int compare(Object obj1, Object obj2) {               // (4)

        // (5) Create reversed versions of the strings.
        String reverseStr1 = new StringBuffer((String) obj1).reverse().toString();
        String reverseStr2 = new StringBuffer((String) obj2).reverse().toString();

        // Compare the reversed strings lexicographically.
        return reverseStr1.compareTo(reverseStr2);               // (6)
    }
}
The program is run with the following program arguments on the command line:
>java ComparatorUsage court Stuart report Resort assort support transport distort
Output from the program using the natural order (1a):
[Resort, Stuart, assort, court, distort, report, support, transport]
Output from the program using the case insensitive order (1b):
[assort, court, distort, report, Resort, Stuart, support, transport]
Output from the program using the rhyming order (1c):
[Stuart, report, support, transport, Resort, assort, distort, court]

No comments:

Post a Comment