Monday 22 July 2013

Difference between Array.sort() and Collections.sort() with example



Difference between Array.sort() and Collections.sort() with example

Program to sort an Array with Arrays.sort() method of util package
import java.util.Arrays;
public class demoCollection1
{

   public static void main(String[] args)
                {

                   String emp[] = {"Saurav","Rahul","Sachin","Prasad","Mongia"};
                    System.out.println("The Array before Sorting");
           for(int i=0;i<5;i++)
           {
              
                System.out.println(emp[i]);
           }
          Arrays.sort(emp);  //This will sort the arrays contents
          System.out.println("The Array after Sorting");
          for(int i=0;i<5;i++)
           {

                System.out.println(emp[i]);
           }
                }
}



Program to sort an ArrayList with Collections.sort() method of util package

import java.util.*;
public class demoCollection2
{
    public static void main(String s[])
    {

        ArrayList al  = new ArrayList();
        al.add("fffff");
        al.add("bbbbb");
        al.add("ddddd");
        al.add("ccccc");
        al.add("aaaaa");
        System.out.println("ArrayList before sorting");
        System.out.println(al);
        Collections.sort(al);
        System.out.println("ArrayList after sorting");
        System.out.println(al);
    }

}

The upper two program can sort array and arraylist on the basis of single values but Lists are meant to store objects and they can have multiple properties so if need to sort list on the basis of some other properties than we need to use Compareable and Comparator interfaces.

No comments:

Post a Comment