Comparable

  • A Comparable object is capable of Comparing itself with another object. The class itself must implement a Comparable interface in order to able to compare its instance.
  • You must modify the class whose instance you want to sort so that only one sort sequence can be created per class.
  • compareTo(b)
  • Comparable is present in the lang package.

public class Student implements Comparable {

int rollNO;
String name;
int age;

Student(int rollNO,String name,int age)
{
this.rollNO = rollNO;
this.name = name;
this.age=age;
}

@Override
public int compareTo(Student st) {
    if(age==st.age)
    {
        return 0;
    }else if(age>st.age)
    {
        return 1;
    }else
    {
        return -1;
    }
}

}

public class Test {
public static void main(String[] args) {
ArrayList arl = new ArrayList();
arl.add(new Student(1,”digi1″,31));
arl.add(new Student(3,”digi3″,33));
arl.add(new Student(2,”digi2″,32));
arl.add(new Student(6,”digi6″,36));

Collections.sort(arl);
for(Student student:arl)
{
    System.out.println(student.age+"-"+student.name+"-"+student.rollNO);
}

}
}

OUTPUT:

31-digi1-1
32-digi2-2
33-digi3-3
36-digi6-6

Comparator

  • A Comparator object is capable of comparing two different objects,The class is not comparing its instances ,but some other class instances .This comparator class must implements the comparator Interface.
  • you build a class seprate from class whose instance you want to sort , so that multiple sort sequence can be created per class.
  • int compare(a,b)
  • A Comparator is present in the Util package.

public class Student {

int rollNO;
String name;
int age;

Student(int rollNO,String name,int age)
{
this.rollNO = rollNO;
this.name = name;
this.age=age;
}

public class AgeComparator implements Comparator {

@Override
public int compare(Student s1, Student s2) {
    if(s1.age==s2.age)
    {
        return 0;
    }else if(s1.age>s2.age)
    {
        return 1;
    }else
    {
        return -1;
    }
}

public class NameComparator implements Comparator {

@Override
public int compare(Student s1, Student s2) {
return s1.name.compareTo(s2.name);
}

}

public class Test {
public static void main(String[] args) {
ArrayList arl = new ArrayList();
arl.add(new Student(1,”digi1″,31));
arl.add(new Student(3,”digi3″,33));
arl.add(new Student(2,”digi2″,32));
arl.add(new Student(6,”digi6″,36));

System.out.println("sort by name");
Collections.sort(arl, new NameComparator());
for(Student student:arl)
{
    System.out.println(student.age+"-"+student.name+"-"+student.rollNO);
}

System.out.println("sort by age");
Collections.sort(arl, new AgeComparator());
for(Student student:arl)
{
    System.out.println(student.age+"-"+student.name+"-"+student.rollNO);
}

}

OUTPUT

—–sort by name—-
31-digi1-1
32-digi2-2
33-digi3-3
36-digi6-6
—–sort by age—–
31-digi1-1
32-digi2-2
33-digi3-3
36-digi6-6