COMPARABLE AND COMMPARATOR IN ARRAYLIST

Comparable and Comparator in ArrayList


sort():

It is one of the important method in ArrayList class.

  • Sort() is present inside Collection class but it is not a part of List interface.
  • sort() is used only for List Interface.
  • By using sort() we can able to sort only List interface values means ArrayList,LinkedList,Vectorsvalues only. But we can’t use for Set & Map Interfaces.

Syntax:

    Collections.sort(List list);

    Collections.sort(List list, Comparator compare);

    • By default Collection.sort() will sort the list elements by using Comparable Interface.

    • Means what are all the objects we want to sort that corresponding class should implement Comparable Interface.

    • Inside Comparable Interface there is only one method and it is named as compareTo(Object obj).

    • If we want to sort the list elements/ Collection elements then that list should contain same type of elements else we getClassCastException.

    • By default sort() will give ascending order of output.

Sorting Rules:

    • List Should contain same type of elements else we will get ClassCastException.
    • Corresponding element class should Implement Comparable Interface and override the compareTo method.

Example1:

 
						
              package com.sdj.pack2;
              public class CollectionSort
              {
                public static void main(String[] args)
                {
                  List l1=new ArrayList();
                  l1.add(10);
                  l1.add(40);
                  l1.add(15);
                  l1.add(30);
                  l1.add(24);
                  l1.add(14);
                  System.out.println(l1);
                  Collections.sort(l1);
                  System.out.println(l1);
                }
              } 
						

Output:

Before sorting list elements: [10, 40, 15, 30, 24, 14] After sorting list elements: [10, 14, 15, 24, 30, 40]

Example2:

 
						
               package com.sdj.pack2;
               public class CollectionSort
               {
                public static void main(String[] args)
                {
                  List l1=new ArrayList();
                  l1.add("pqr");
                  l1.add("dbf");
                  l1.add("eir"):
                  l1.add("abc");
                  l1.add("jfe");
                  l1.add("ram");
                  System.out.println(l1);
                  Collections.sort(l1);
                  System.out.println(l1);
                }
              }						

Output:

Before sorting list elements: [pqr, dbf, eir, abc, jfe, ram] After sorting list elements: [abc, dbf, eir, jfe, pqr, ram] -- sorted in ascending order

Example3:

 
						
               package com.sdj.pack2;
               public classm CollectionSort
               {
                public static void main(String[] args)
                {
                  List l1=new ArrayList();
                  l1.add("pqr");
                  l1.add("dbf");
                  l1.add(12);
                  l1.add(52);
                  l1.add(12.2);
                  l1.add("eir");
                  l1.add("abc");
                  l1.add("jfe");
                  l1.add("ram");
                  System.out.println(l1);
                  Collections.sort(l1);// here we will get RTE i.eClassCastException
                  System.out.println(l1);
                }
              }                     	

Output:

     [pqr, dbf, 12, 52, 12.2, eir, abc, jfe, ram]
     
     

Explanation:

    From above program we will get ClassCastExceptioni.e RTE at Collections.sort(list) line, why because list object is containing different data types of elements. For sorting operation it should contain same type elements.

Sorting List objects based on Comparator object:

  • if we want to sort the list objects based on java.uitl.Comparator interface ,Then we should Pass Comparator class object to the sort method as second parameter along with List object.

  • By using Comparator interface we can sort the elements with different conditions, like sort the person objects based on age or sort based on height or weight etc….. But for every condition we should create the indusial class by making sub class to Comparator interface and we need to override the compare(Object obj1,Object obj2) method.

Example4:

 
						
               package com.sdj.pack1;
               class Person
               {
                int age;
                double height;
                Person(int age,double height)
                {
                  this.age=age;
                  this.height=height;
                }
                public String toString()
                {
                  return "age:"+age+",height:"+height;
                }
                public int compareTo(Object obj)
                {
                  return this.age-((Person)obj).age;
                }
              }
              class SortBasedOnAge implements Comparator
              {
                public int compare(Object obj1,Object obj2)
                {
                  Person p1=(Person)obj1;
                  Person p2=(Person)obj2;
                  return   p1.age - p2.age;
                }
              }
              public class Bank
              {
                public static void main(String[] args)
                {
                  List l1=new ArrayList();
                  l1.add(new Person(24,7.5));
                  l1.add(new Person(33,5.5));
                  l1.add(new Person(12,8.5));
                  l1.add(new Person(20,4.5));
                  System.out.println(l1);
                  Collections.sort(l1,new SortBasedOnAge());
                  System.out.println(l1);
                }
              }						  

Output:

List of Persons Before Sorting : [age:24,height:7.5, age:33,height:5.5, age:12,height:8.5, age:20,height:4.5] List of Persons after Sorting based on Age through Comparator: [age:12,height:8.5, age:20,height:4.5, age:24,height:7.5, age:33,height:5.5]
    Note

    Suppose If we want to sort the same person class objects based on Height ,then we should write one more separate class making sub class to Comparator as same as SortBasedOnAge class..

For Details see the bellow Example:

 
						
               public class SortBasedOnHeight implements Comparator
               {
                public int compare(Object obj1,Object obj2)
                {
                  Person p1=(Person)obj1;
                  Person p2=(Person)obj2;
                  return ((Double)(p1.height-p2.height)).intValue();
                }
              }
              public class Army
              {
                public static void main(String[] args)
                {
                  List l1=new ArrayList();
                  l1.add(new Person(24,7.5));
                  l1.add(new Person(33,5.5));
                  l1.add(new Person(12,8.5));
                  l1.add(new Person(20,4.5));
                  // Here person class objects please refer above example person class program only
                  System.out.println(l1);
                  Collections.sort(l1,new SortBasedOnHeight());
                  System.out.println(l1);
                }
              }                    

Output:

List of Persons before Sorting: [age:24,height:7.5, age:33,height:5.5, age:12,height:8.5, age:20,height:4.5] List of Persons after Sorting based on Age through Comparator: [age:20,height:4.5, age:33,height:5.5, age:24,height:7.5, age:12,height:8.5] -------------------> In Ascending order