Posts

Showing posts from October 14, 2010

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; /*If you want to desc order*/ //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(&

Recent Post

Recent Posts Widget