Author: gnuhpc
Source: http://www.cnblogs.com/gnuhpc/
// Create a comparator that returns the outcome
// Of a reverse string comparison.
Class revstrcomp implements comparator <string> {
// Implement the compare () method so that it
// Reverses the order of the string comparison.
Public int compare (string stra, string strb) {// compare strb to stra, rather than stra to strb.
Return strb. compareto (stra );
}
}
// Sort an array of strings in reverse order.
Import java. util .*;
// Create a comparator that returns the outcome
// Of a reverse string comparison.
Class revstrcomp implements comparator <string> {
// Implement the compare () method so that it
// Reverses the order of the string comparison.
Public int compare (string stra, string strb ){
// Compare strb to stra, rather than stra to strb.
Return strb. compareto (stra );
}
}
// Demonstrate the reverse string comparator.
Class revstrsort {
Public static void main (string ARGs []) {
// Create a sample array of strings.
String STRs [] = {"dog", "horse", "ZEBRA", "cow", "cat "};
// Show the initial order.
System. Out. Print ("initial order :");
For (string S: STRs)
System. Out. Print (S + "");
System. Out. println ("/N ");
// Sort the array in reverse order.
// Begin by creating a reverse string comparator.
Revstrcomp RSC = new revstrcomp ();
// Now, sort the strings using the reverse comparator.
Arrays. Sort (STRs, RSC );
// Show the reverse sorted order.
System. Out. Print ("sorted in reverse order :");
For (string S: STRs)
System. Out. Print (S + "");
System. Out. println ("/N ");
// For comparison, sort the strings in natural order.
Arrays. Sort (STRs );
// Show the natural sorted order.
System. Out. Print ("sorted in natural order :");
For (string S: STRs)
System. Out. Print (S + "");
System. Out. println ("/N ");
}
}
Output:
Initial order: Dog horse zebra cow cat
Sorted in reverse order: Zebra horse dog cow cat
Sorted in natural order: cat cow dog horse zebra
Author: gnuhpc
Source: http://www.cnblogs.com/gnuhpc/