Also available as ArrayListSort.java

/**
 * Title: ArrayListSort
 * Description: Simple example of using the sort method with an ArrayList
 * @author hollingd@cs.rpi.edu
 */
import java.util.*;

class MyIntComparator implements Comparator {

    // reverses the natural sort order
    public int compare( Object o1, Object o2) {
        int x1 = ((Integer)o1).intValue();
        int x2 = ((Integer)o2).intValue(); 

        if (x1 > x2) return(-1);
        else if (x1 < x2 ) return(1);
        else return(0);
    }
}




class ArrayListSort {

    public static void main(String [] args ) {

        // Create an ArrayList object
        ArrayList x = new ArrayList();

        // Populate with 10 random Integer objects
        Random r = new Random();

        for (int i=0;i<10;i++) {
            x.add( new Integer(r.nextInt(100)));
        }

        System.out.println("------ Initial Order -----");
        // print using random access (get)
        for (int i=0;i<x.size();i++) {
            // Extract an object from the ArrayList and convert to int
            //   (could also give Integer object to println as well...
            int y = ((Integer) x.get(i)).intValue();
            System.out.println("x["+i+"] = " + y);
        }


        // Sort the ArrayList (possible because Integer implements
        //  the interface Comparable)
        Collections.sort((List)x);


        // print new order
        // print using random access (get)
        System.out.println("------ sorted using sort() -----");
        for (int i=0;i<x.size();i++) {
            // Extract an object from the ArrayList and convert to int
            //   (could also give Integer object to println as well...
            int y = ((Integer) x.get(i)).intValue();
            System.out.println("x["+i+"] = " + y);
        }

        // Sort the ArrayList using myIntComparator

        Collections.sort((List)x,new MyIntComparator());

        // print new order
        // print using random access (get)
        System.out.println("------ sorted using sort( MyIntComparator) -----");
        for (int i=0;i<x.size();i++) {
            // Extract an object from the ArrayList and convert to int
            //   (could also give Integer object to println as well...
            int y = ((Integer) x.get(i)).intValue();
            System.out.println("x["+i+"] = " + y);
        }

    }

}