The Compare Method:: Sorted Order
The Compare Method:: Sorted Order
However, it is the comparator that defines precisely what sorted order means. The Comparator interface defines two methods: compare( ) and equals( ). The compare( ) method, shown here, compares two elements for order:
Example:
class Dog implements Comparator<Dog>, Comparable<Dog>{ private String name; private int age; Dog(){ }
// Overriding the compare method to sort the age public int compare(Dog d, Dog d1){ return d.age - d1.age; } }
public static void main(String args[]){ // Takes a list o Dog objects List<Dog> list = new ArrayList<Dog>();
list.add(new Dog("Shaggy",3)); list.add(new Dog("Lacy",2)); list.add(new Dog("Roger",10)); list.add(new Dog("Tommy",4)); list.add(new Dog("Tammy",1)); Collections.sort(list);// Sorts the array list
// Sorts the array list using comparator Collections.sort(list, new Dog()); System.out.println(" "); for(Dog a: list)//printing the sorted list of ages System.out.print(a.getDogName() +" a.getDogAge() + ", "); } } This would produce the following result: Lacy, Roger, Shaggy, Tammy, Tommy, Tammy : 1, Lacy : 2, Shaggy : 3, Tommy : 4, Roger : 10, : "+