//sortVec.java --- demo using Collections.sort(Vector) // @CopyLeft by tsaiwn@csie.nctu.edu.tw //Java Vector is a List import java.util.*; import java.io.*; class God implements Comparator { public int compare(String x, String y) { System.out.print(" haha "); return y.compareTo(x); // C: return strcmp(y.c_str( ), x.c_str( ) ) < 0; } }; public class sortVec { PrintStream cout = System.out; public static void main(String xxx[ ]) { new sortVec( ); } sortVec( ) { main( ); } void printVector(Vector x) { for(int i=0; i< x.size( ); ++i) cout.print( " "+ x.get(i)); cout.println( ); } /// Java String is an Object, we can use Comparator on sorting // Java Arrays.sort( ), Collections.sort( ) are Stable (merger sort) int main ( ) { Vector xx = new Vector( ); xx.add("aaa"); xx.add("ccc"); xx.add("bbb"); xx.add("BBS"); xx.add("egg"); xx.add("EGG_BIG"); cout.print("Vector xx: "); printVector(xx); Collections.sort(xx); // ascending cout.print("\n=== after sort\n Vector xx: "); printVector(xx); cout.print("\n=== now calling sort with God arben "); God arben = new God( ); // a Comparator Collections.sort(xx, arben); cout.print("\n=== after sort(xx, arben)\n Vector xx: "); printVector(xx); Sorter bobo = new Sorter( ); // with compare_nocase Collections.sort(xx , bobo); cout.print("\n=== after sort(xx, bobo)\n Vector xx: "); printVector(xx); return 0; } // main( }// class class Sorter implements Comparator { public int compare(String first, String second) { return first.compareToIgnoreCase(second); } } // class Sorter /****** D:\COURSE\OOP\ppnt>javac sortVec.java D:\COURSE\OOP\ppnt>java sortVec Vector xx: aaa ccc bbb BBS egg EGG_BIG === after sort Vector xx: BBS EGG_BIG aaa bbb ccc egg === now calling sort with God arben haha haha haha haha haha haha haha haha haha haha haha haha haha haha haha === after sort(xx, arben) Vector xx: egg ccc bbb aaa EGG_BIG BBS === after sort(xx, bobo) Vector xx: aaa bbb BBS ccc egg EGG_BIG D:\COURSE\OOP\ppnt> *******************************/