2

I am implementing Comparator and Comparable in my class Employee to sort an arraylist. I am sorting on 2 parameters name and ID. While sorting with ID using Collections.sort(Employee ob1, Employee ob2) it doesn't work. I get the compilation error that the class is not declared abstact and i am not overriding compare(), although i am doing it as:

public int compare(Employee ob1, Employee ob2)
{
return ob1.id-ob2.id;
}

it works fine if i use

public int compare(Object ob1, Object ob2)
{
return ((Employee)ob1).id-((Employee)ob2).id;
}

My doubt is why does't the earlier one work since Employee is also an Object. The same issue is with compareTo(Object ob) as well, While overriding why can't i use Employee directly and why do i need to use Object there and later need to cast it to Employee class.

Megan
  • 876
  • 2
  • 10
  • 20

2 Answers2

5

Polymorphism, using Object, Object overrides a raw-type in Comparator. Using your class names doesn't match that signature. For a compile error when you mix up the signature use the template type.

public class Employee implements Comparator<Employee> {
  // ....
  @Override
  public int compare(Employee ob1, Employee ob2) {
    return ob1.id-ob2.id;
  }
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

You need to implement the exact methode the interface defines. If you want to work directly with your Object use the <> generic syntax:

public class Employee implements Comparator<Employee> 
{
   @Override
   public int compare(Employee ob1, Employee ob2) 
   {
      return ob1.id - ob2.id;
   }

}

Make sure to use the @Override Annotation. This will give you a compiler warning if you get the methode wrong (parameter, return values etc.)

When using Comparable you can use it like this:

public class Employee implements Comparable<Employee> 
{
   @Override
   public int compareTo(Employee e) 
   {
      //your compare code
   }
}

See also: Comparable vs Comparator

Community
  • 1
  • 1
HectorLector
  • 1,851
  • 1
  • 23
  • 33