    1 //sortTest.java -- by tsaiwn@csie.nctu.edu.tw
    2 import java.io.*;
    3 import java.util.*;
    4 class Stu implements Comparable {
    5     long sid;
    6     double height;
    7     double wet;
    8     Stu(long a, double b, double c) {sid=a; height=b; wet=c;}
    9     public int compareTo(Object o2){
   10         Stu b = (Stu) o2;
   11         if(sid > b.sid) return 1;   // ascending order
   12         else if(sid < b.sid) return -1;
   13         return 0;
   14     }
   15 }; // struct Stu
   16 class sortTest {
   17    static int yyy[ ] = { 1, 2, 3, 4, 5, 6 };
   18    static Stu x[ ] = {  new Stu(921, 175.0, 60.0),
           new Stu(911, 172.0, 58.0), 
   19        new Stu(933, 168., 58.), new Stu(915, 168.5, 56.8), 
   20        new Stu(938, 170.0, 68.5) };
   21    public static void main(String xxx[ ]) {
   22        cout.println("Original data ..");
   23        print(x); 
   24        cout.println("After Arrays.sort(x)");
   25        Arrays.sort(x);  print(x);
   26        SortAA<Stu> ar3 = new SortAA<Stu> ( );
   27        cout.println("After Arrays.sort(x, 0, x.length, ar3)");
   28        Arrays.sort(x, 0, x.length, ar3); print(x);   
   29 //
   30        SortBB lee4 = new SortBB( );
   31        cout.println("After Arrays.sort(x, 0, x.length, lee4)");
   32        Arrays.sort(x, 0, x.length, lee4); print(x);        
   33    } // main
   34    static PrintStream cout=System.out;
   35    static void print(Stu y[ ]) {     
   36       for(int i=0; i < y.length; ++i) {
   37          cout.println(""+y[i].sid + "  " + y[i].height +
   38                "  " + y[i].wet);
   39       } // for
   40       cout.println("=== ===");
   41    }
   42 } // sortTest
   43 class SortAA<T> implements Comparator<T>  {
   44     public int compare(T aa, T bb) {
   45        Stu a = (Stu)aa; Stu b = (Stu)bb;
   46        if(a.height < b.height) return 1;   // height Descending
   47        else if(a.height > b.height) return -1;// compare other field ?
   48        if(a.sid > b.sid) return 1;
   49        else if(a.sid < b.sid) return -1;
   50        return 0;  // equals
   51     } // compare
   52 } // SortAA
   53 class SortBB implements Comparator  {
   54     public int compare(Object aa, Object bb) {
   55        Stu a = (Stu)aa; Stu b = (Stu)bb;
   56        if(a.wet < b.wet) return 1;   // wet Descending
   57        else if(a.wet > b.wet) return -1;// compare other field ?
   58        if(a.sid > b.sid) return 1;
   59        else if(a.sid < b.sid) return -1;
   60        return 0;  // equals
   61     } // compare
   62 } // SortBB

