Comparators interface in java

Comparators interface

  • This interface is needed for the TreeSet & TreeMap where elements are in sorted order.
  • It defines 2 methods
    • int compare(Object obj1, Object obj2)
    • boolean equals(Object obj)
  • int compare(Object obj1, Object obj2): It is used to compare 2 objects. This method returns zero if the objects are equal. It returns a positive value if obj1 is greater than obj2. Otherwise, a negative value is returned.
  • boolean equals(Object obj): specifies whether another object is equal to this comparator.┬áIf ob1 is less then it returns -1. If ob1 & ob2 are equal then it returns 0. If ob1 is greater then it returns 1.
Write a program that shows the use of comparator interface
import java.util.*;
import java.util.Collections;
class Dog implements Comparator, Comparable
{
private String name;
private int age;
Dog()
{
}
Dog(String n, int a)
{
name = n;
age = a;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public int compareTo(Dog d)
{
return(this.name).compareTo(d.name);
}
public int compare(Dog d, Dog d1)
{
return d.age – d1.age;
}
}
public class test
{
public static void main(String args[])
{
List li = new ArrayList();
li.add(new Dog(“Sheru”, 3));
li.add(new Dog(“Rocky”, 2));
li.add(new Dog(“Tommy”, 10));
li.add(new Dog(“Shaggy”, 4));
li.add(new Dog(“Moti”, 1));
Collections.sort(li);
for(Dog a: li)
System.out.print(a.getName() + “, “);
Collections.sort(li, new Dog());
System.out.println(” “);
for(Dog a: li)
System.out.print(a.getName() +” : “+ a.getAge() + “, “);
}
}

Output:
Moti, Rocky, Shaggy, Sheru, Tommy,
Moti : 1, Rocky : 2, Sheru : 3, Shaggy : 4, Tommy : 10,

Leave a Reply

Your email address will not be published. Required fields are marked *