Comparable vs Comparator



Comparbale:

This interface present in java.lang package and it contains only one method compareTo(object)
public int comapreTo(Object obj)
Example:obj1.compareTo(obj2)
it it returns -ve if obj1 has come before object2
it it  returns +ve if obj1 has come after object2
returns '0' if object1 and object2 are equal
 based on our requirement we need to return +ve or -ve(i means ascending or descending order)

Example:


package com.collections;
public class ComparableDemo {


public static void main(String[] args) {  

System.out.println("a".compareTo("z"));//-25
System.out.println("b".compareTo("z"));//-24
System.out.println("c".compareTo("z"));//-23
System.out.println("z".compareTo("a"));//25
}

}

Base on this values only TreeSet add method arranging elements _ve means before  +ve means
after.we no need to call this method explicitly TreeSet add method will call for arranging the elements.

If we are not satisfied with default sorting order or if default is not aviliable

then we can define our own sorting order using Comparator object 

Comparable meant for default natural sorting order where as Compartor meant for customized sorting order.

Compartor:

  Compartor interface present in java.util package and it contains two methods

1.public int compare(Object obj1,Object obj2);

it it returns -ve if obj1 has come before object2
it it  returns +ve if obj1 has come after object2
returns '0' if object1 and object2 are equal

2.public boolean equals(Object o)

TreeSetExample(default sorting order means Comparble ):


package com.collections;
import java.util.TreeSet;
public class TreeSetExample {
public static void main(String[] args) {
TreeSet<Integer> numbersInOrder=new TreeSet<Integer>();
numbersInOrder.add(10);
numbersInOrder.add(99);
numbersInOrder.add(1);
 System.out.println(numbersInOrder+":::TreeSet elemnts");
}
}

output:    [1, 10, 99]:::TreeSet elemnts

Note:Integer Class implements Comparble interface so it fallows natural sorting order


TreeSetExample(cutomized sorting order means using compare):

package com.collections;
import java.util.Comparator;

import java.util.TreeSet;

public class CompartorDemo implements Comparator {

public static void main(String[] args) { 

TreeSet<Integer> numbersInOrder=new TreeSet<Integer>(new CompartorDemo()); numbersInOrder.add(10); 

numbersInOrder.add(99);

numbersInOrder.add(1); 

System.out.println(numbersInOrder+":::TreeSet elemnts");

}
@Overridepublic int compare(Object o1, Object o2) {  

Integer number1=(Integer)o1; Integer number2=(Integer)02;

if(number1>number2){ 

return -1;

}else if(number1<number2){

return +1;

}

return 0;

}

}
  output:   [99, 10, 1]:::TreeSet elemnts

Note:

CompartorDemo 

 Class implements Compator interface so it fall ows customized  sorting order


Comparable Vs Comaprator

1.When we need to go for Comparable or Comaprator is

If we are not satisfied with default sorting order or if default is not aviliable

then we can define our own sorting order using Comparator object 

Comparable meant for default natural sorting order where as Compartor meant for customized sorting order.

2.For predefined non-comparable classes default natural sorting order is not available we can define sorting order using by using comparator .


3.for user defined  classes (our own classes )we can define natural sorting order by implementing Comparable interface.


4.The other person who is using our class he is not satisfy with default natural sorting order then he can define his own sorting by using comparator.

Defining sorting order for userdefined classes using Compartor and Comparble:

Here i am giving two examples .consider we need to sort the student objects based on rollno
so i am implementing Comparble for default sorting order  and first time i fallow asending order
next example i need rollno in descending order so i use Comparator 

Examples:


Student class implenetsComparable interface for arranging students based on rollno
ascending order 



package com.collections;
public class Student implements Comparable<Student> {
Integer roolno;
String name;
public Integer getRoolno() {
return roolno;
}
public void setRoolno(Integer roolno) {
this.roolno = roolno;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Student [roolno=" + roolno + ", name=" + name + "]";
}
public Student(int roolno, String name) {
super();
this.roolno = roolno;
this.name = name;
}
@Override
public int compareTo(Student student2) {
Integer rollno1 = this.roolno;
Integer rollno2 = student2.getRoolno();
if (rollno1 > rollno2) {
return +1;
} else if (rollno1 < rollno2) {
return -1;
}
return 0;
}
}

In this below example we are adding student objects into  TreeSet
package com.collections;
import java.util.TreeSet;
public class CompableStudentDemo {
public static void main(String[] args) {
Student student1=new Student(50, "surendra");
Student student2=new Student(10, "ram");
Student student3=new Student(90, "kumar");
Student student4=new Student(100, "suri");
TreeSet<Student> students=new TreeSet<Student>();
students.add(student1);
students.add(student2);
students.add(student3);
students.add(student4);
System.out.println("student list"+students);
}
}

output:

student list[Student [roolno=10, name=ram], Student [roolno=50, name=surendra], Student [roolno=90, name=kumar], Student [roolno=100, name=suri]]

objets are printed based rollno ascending order


Example2:Another example arranging students based on rollno but descending order in above example order is already order is defined but its ascending order so we need to to use Compartor to customize sorting order 

package com.collections;
import java.util.Comparator;
public class CustoziedStudent implements Comparator<Student> {
@Override
public int compare(Student student1, Student student2) {
if(student1.getRoolno()>student2.getRoolno()){
return -1;
}
else if(student1.getRoolno()>student2.getRoolno()){
return 1;
}
return 0;
}
}

In this below class we are using above CustoziedStudent class  for customized sorting order

package com.collections;
import java.util.TreeSet;
public class ComparatorStudentDemo {
public static void main(String[] args) {
Student student1=new Student(50, "surendra");
Student student2=new Student(10, "ram");
Student student3=new Student(90, "kumar");
Student student4=new Student(100, "suri");
TreeSet<Student> students=new TreeSet<Student>(new CustoziedStudent());
students.add(student1);
students.add(student2);
students.add(student3);
students.add(student4);
System.out.println("student list"+students);
}
}

output:

student list[Student [roolno=100, name=suri], Student [roolno=90, name=kumar], Student [roolno=50, name=surendra]]

Students are arranged based on roolno in descending order..


Author

Written by Admin

Aliquam molestie ligula vitae nunc lobortis dictum varius tellus porttitor. Suspendisse vehicula diam a ligula malesuada a pellentesque turpis facilisis. Vestibulum a urna elit. Nulla bibendum dolor suscipit tortor euismod eu laoreet odio facilisis.

0 comments: