Comparable vs. Comparator in java
Comparable vs. Comparator
Comprable interface is used for natural ordering of any object.
Comprable interface is the part of lava.lang package.
Suppose you have a class named Car had have attribute name carName and engPower and want to ordering according to carName.
Car class must implements Comparable interface.
class Car implements Comparable{
private String carName;
public String getCarName() {
return carName;
}
public void setCarName(String carName) {
this.carName = carName;
}
// sort for car name
public int compareTo(Object obj) {
Car car = (Car)obj;
//return car.carName.compareTo(this.carName);
/*If you want to asc order*/
return this.carName.compareTo(car.carName);
}
}
public class Test {
public static void main(String[] args) throws IOException {
Car car1 = new Car();
Car car2 = new Car();
Car car3 = new Car();
car1.setCarName("Safari");
car2.setCarName("Scorpio");
car3.setCarName("Alto");
List list = new ArrayList();
list.add(car1);
list.add(car2);
list.add(car3);
Collections.sort(list);
for(int i=0; i<list.size(); i++){
Car car=(Car)list.get(i);
System.out.println(car.getCarName());
}
}
}
Comparator interface is used for compare two object of same class.
Comparator interface is the part of java.util.
Same example using Comparator interface is below
class Car{
private String carName;
private int engPower;
public String getCarName() {
return carName;
}
public void setCarName(String carName) {
this.carName = carName;
}
public int getEngPower() {
return engPower;
}
public void setEngPower(int engPower) {
this.engPower = engPower;
}
}
class CarComparator implements Comparator {
public int compare(Object arg0, Object arg1) {
Car car = (Car)arg0;
Car car1 = (Car)arg1;
return car.getCarName().compareTo(car1.getCarName());
}
}
public class Test {
public static void main(String[] args) throws IOException {
Car car1 = new Car();
Car car2 = new Car();
Car car3 = new Car();
car1.setCarName("Ritz");
car2.setCarName("Ballano");
car3.setCarName("Alto");
List list = new ArrayList();
list.add(car1);
list.add(car2);
list.add(car3);
Collections.sort(list, new CarComparator());
for(int i=0; i<list.size(); i++){
Car car=(Car)list.get(i);
System.out.println(car.getCarName());
}
}
}
compareTo() method of comparable takes one object and return int value.
compare() method of comparator takes two object and return int value.
Int value can be negative, zero, positive
negative value indicates for ascending order.
Zero value indicates for no order.
Negative value indicates for descending order.
Comments
Post a Comment