//sortList.java --- demo to sort List in Java // modified from C++ STL example of list // modified by tsaiwn@csie.nctu.edu.tw import java.util.*; class sortList { java.io.PrintStream cout = System.out; public static void main(String xx[ ]) { new sortList( ); } sortList( ) { main( ); } // the following is a Comparator class SorterIgCase implements Comparator { // comparison, not case sensitive. //bool compare_nocase (string first, string second) // C++ public int compare(String first, String second) { return first.compareToIgnoreCase(second); } }// class SorterIgCase int main ( ) { //List aList = new LinkedList( ); List aList = new ArrayList( ); aList.add ("one"); aList.add ("two"); // push_back( ) in C++ STL aList.add ("Three"); aList.add("Four"); aList.add("five"); aList.add(0, "ZERO_haha"); // head (push_front in C++ STL) aList.add("six"); cout.print("mylist contains: "); printList(aList); //aList.sort(); // C++ STL // Note that there is NO function sort(list) in C++ STL Collections.sort(aList); cout.print("After sort( ),\nmylist contains: "); printList(aList); //aList.sort(compare_nocase); SorterIgCase compare_nocase = new SorterIgCase( ); Collections.sort(aList, compare_nocase); cout.print("After sort(compare_nocase),\nmylist contains: "); printList(aList); cout.println("After sort with Collections.reverseOrder :"); Collections.sort(aList, Collections.reverseOrder(compare_nocase)); printList(aList); return 0; } // int main( // use an iterator to traverse a Linked List void printList(List myList) { // a generic function Iterator it = myList.iterator( ); for( ; it.hasNext( ); ) cout.print(" " + it.next( )); // Iterator cout.println( ); } // printList( } // class /****** D:\COURSE\OOP\ppnt>javac sortList.java D:\COURSE\OOP\ppnt>java sortList mylist contains: ZERO_haha one two Three Four five six After sort( ), mylist contains: Four Three ZERO_haha five one six two After sort(compare_nocase), mylist contains: five Four one six Three two ZERO_haha After sort with Collections.reverseOrder : ZERO_haha two Three six one Four five *******************************/