free web hosting | free hosting | Web Hosting | Free Website Submission | shopping cart | Promoter Online | php hosting
affordable web hosting Pets web page hosting web hosting website hosting web hosting service web hosting web host
Sorting the Index of Java ArrayList

Sorting the Index of Java ArrayList

Sorting Java ArrayList is easy. Once converted to an Object array, the Arrays.count(Object[]) method will sort the ArrayList for you. Now, what if you only want the index of the ArrayList to be sorted? What if another ArrayList is associated with the order of that ArrayList?

Here is the solution. Suppose you have an ArrayList named count.


   ArrayList count=new ArrayList();

Let n be the size of the ArrayList.


   int n=count.size();

The index which will be sorted should be an Integer array. Construct the array, and set the default value. By default, the index should indicate the natural order of the array, namely, natural number starting from zero to the size of the array.


   Integer index[]=new Integer[n];
   for(int i=0;i<n;i++)
       index[i]=new Integer(i);

Let's sort the array. The Arrays.sort(Object[],Comparator) method takes the Integer[] index and a Comparator interface as arguments. The Comparator interface defines the comparison method. Here, the interface is declared as an inner interface, defining compare(Object,Object) method where elements of the ArrayList are compared. The int values of n1 and n2 are simply the int values of the Integer's. Get the element value by calling ArrayList.get(int) method, and return the result of the comparison by calling Integer.compareTo(Integer) method.


  Arrays.sort(index,new Comparator()
    {
	public int compare(Object obj1, Object obj2)
	{
	    int n1=((Integer)obj1).intValue();
	    int n2=((Integer)obj2).intValue();
	    return ((Integer)count.get(n1)).compareTo((Integer)count.get(n2));
	}
    });	

Now, the index array is sorted. It is sorted in the ascending order of the ArrayList count. If n1 and n2 values are replaced in compareTo method, the index will be sorted in the descending order of the ArrayList.


Return to Home Page
Erica Asai
Last Modified: Fri Sep 03 11:47:37 2004