When to use Comparator and when to use Comparable in Java?

I have an Employee class that has 3 fields as shown below.

class Employee 
{
  private int empId;
  private String empName;
  private int empAge;

  public Employee(int empId, String empName, int empAge) {
    this.empId = empId;
    this.empName = empName;
    this.empAge = empAge;
}

 // setters and getters

      

For this, I want to sort based on Employee Name (empName) if multiple employees have the same name, then sort based on employee ID (empId).

For this, I wrote a custom comparator using java.util.Comparator as shown below.

   class SortByName implements Comparator<Employee> 
   {
      public int compare(Employee o1, Employee o2) {
       int result = o1.getName().compareTo(o2.getName());
      if (0 == result) {
        return o1.getEmpId()-o2.getEmpId();
    } else {
        return result;
    }
   }
  }

      

I have created 8 Employee objects and added to the ArrayList as shown below.

    List<Employee> empList = new ArrayList<Employee>();

    empList.add(new Employee(3, "Viktor", 28));
    empList.add(new Employee(5, "Viktor", 28));
    empList.add(new Employee(1, "Mike", 19));
    empList.add(new Employee(7, "Mike", 19));
    empList.add(new Employee(4, "Mark", 34));
    empList.add(new Employee(6, "Jay", 34));
    empList.add(new Employee(8, "Gayle", 10));
    empList.add(new Employee(2, "Gayle", 10));          

      

And sorting the list as shown below using the above comparator.

Collections.sort(empList,new SortByName());

      

Everything went perfectly. But it can be done using Comparable as shown below.

class Employee implements Comparable<Employee> {
private int empId;
private String name;
private int age;

public Employee(int empId, String name, int age) {
    this.empId = empId;
    this.name = name;
    this.age = age;
}

//setters and getters

@Override
public int compareTo(Employee o) {
    int result = this.getName().compareTo(o.getName());
    if (0 == result) {
        return this.getEmpId()-o.getEmpId();
    } else {
        return result;
    }

}

}

      

Sorting the list using Collections.sort (empList);

So, I want to know what is use case or where exactly do we use these both? I realized that Comparable is used for natural sorting and can only sort one field, while the comparator is used to sort multiple fields. But, if we see my example, both interfaces have the ability to do both. So please explain to me what are the unique features of these and those where others cannot be used.

+3


source to share


3 answers


Use Comparable if you want to define the default (natural) ordering behavior of the object in question, a common practice is to use a technical or natural (database?) Object identifier for this.



Use the Comparator when you want to define an external managed ordering behavior, this can override the default ordering behavior. You can define any number of ordering operations that you can use as needed.

+2


source


There are classes that define order by nature (eg String

[lexicographic order is the de facto standard] or Date

s). For these classes, you can define their natural order by implementing Comparable<T>

. But as I will sketch, many classes can be orderd in more than one way. It is Comparator<T>

extremely useful for this .

Ok, let's look at another example. Imagine you have a list Employee

, as you mentioned, and want to do something else. For example: you want to flexibly sort them by name OR by income OR by date of birth OR ... (imagine you want to choose how to order them). In this case, you can specify the exact one Comparator

to use depending on the string you chose to sort after.



Another example: the class Employee

already exists and specifies some order, but you are not satisfied with this order. Now you can simply specify your own ordering with Comparator

and get the behavior you want.

0


source


If you really want to know the unique feature of both.

Comparable implementation allows you to compare your class to another class.

Employee implements Comparable<Integer>

      

A comparator is an algorithm for comparing two instances of the same class type.

0


source







All Articles