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.

2
  • 3
    How did you declare your comparator? As Comparator or Comparator<Employee>? Commented Jul 16, 2014 at 13:00
  • 2
    @tobias_k obviously Comparator Commented Jul 16, 2014 at 13:00

2 Answers 2

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;
  }
}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.