Difference Between Comparable and Comparator Interface?
>> Monday, May 30, 2011
Comparable interface:
1.The “Comparable” allows itself to compare with anothersimilar object (i.e. A class that implements Comparable
becomes an object to be compared with). The method
compareTo() is specified in the interface.
2.Many of the standard classes in the Java library like String,
Integer, Date, File etc implement the Comparable interface
to give the class a "Natural Ordering". For example String
class uses the following methods:
3.public int compareTo(o)
public int compareToIgnoreCase(str)
4.
public class Pet implements Comparable { int petId; String petType; public Pet(int argPetId, String argPetType) { petId = argPetId; this.petType = argPetType; } public int compareTo(Object o) { Pet petAnother = (Pet)o; //natural alphabetical ordering by type //if equal returns 0, if greater returns +ve int, //if less returns -ve int return this.petType.compareTo(petAnother.petType); } public static void main(String[] args) { List list = new ArrayList(); list.add(new Pet(2, "Dog")); list.add(new Pet(1, "Parrot")); list.add(new Pet(2, "Cat")); Collections.sort(list); // sorts using compareTo method for (Iterator iter = list.iterator(); iter.hasNext();) { Pet element = (Pet) iter.next(); System.out.println(element); } } public String toString() { return petType; } }Output: Cat, Dog, Parrot
Comparator interface:
1.The Comparator is used to compare two different objects. Thefollowing method is specified in the Comparator interface.
public int compare(Object o1, Object o2)
2.You can have more control by writing your Comparator class. Let us
write a Comparator for the Pet class shown on the left. For most cases
natural ordering is fine as shown on the left but say we require a
special scenario where we need to first sort by the “petId” and then by
the “petType”. We can achieve this by writing a “Comparator” class.
3.
public class PetComparator implements Comparator, Serializable{ public int compare(Object o1, Object o2) { int result = 0; Pet pet = (Pet)o1; Pet petAnother = (Pet)o2; //use Integer class's natural ordering Integer pId = new Integer(pet.getPetId()); Integer pAnotherId = new Integer(petAnother.getPetId()); result = pId.compareTo(pAnotherId); //if ids are same compare by petType if(result == 0) { result= pet.getPetType().compareTo (petAnother.getPetType()); } return result; } public static void main(String[] args) { List list = new ArrayList(); list.add(new Pet(2, "Dog")); list.add(new Pet(1, "Parrot")); list.add(new Pet(2, "Cat")); Collections.sort(list, new PetComparator()); for (Iterator iter = list.iterator(); iter.hasNext();){ Pet element = (Pet) iter.next(); System.out.println(element); } } }Output: Parrot, Cat, Dog.
0 comments:
Post a Comment