This is one of the most important questions that every Java developer should know for collection-related interviews. Comparable and Comparator are two of the most commonly used interfaces in Java for sorting collection classes such as ArrayList, HashSet, and others.
Difference between Comparable and Comparator:-
- The Comparator interface is part of the java.util package, indicating that it is a utility interface used for custom sorting. In contrast, the Comparable interface belongs to the java.lang package, which means it is a fundamental interface available to all Java objects for defining their natural ordering.
- The Comparable interface allows only a single natural ordering of objects, while the Comparator interface enables multiple custom sorting orders to be defined.
The Comparator interface in Java provides the
In contrast, the Comparable interface provides thepublic int compare(Object o1, Object o2)method, which returns a negative integer, zero, or a positive integer depending on whether the first argument is less than, equal to, or greater than the second argument.public int compareTo(Object o)method, which returns a negative integer, zero, or a positive integer depending on whether the current object is less than, equal to, or greater than the specified object.
- If you observe closely, the key logical difference between these two interfaces is that the Comparator interface compares two objects provided to it, whereas the Comparable interface compares the current object (
thisreference) with the specified object.
- Comparable in Java is used to define the natural ordering of objects. In the Java API, classes such as String, Date, and the wrapper classes implement the Comparable interface. It is generally considered a good practice to override the
compareTo()method for value objects.
- If a class implements the Comparable interface in Java, a collection of its objects, such as a List or an Array, can be sorted automatically using the
Collections.sort()orArrays.sort()method. The objects will be sorted according to the natural ordering defined by thecompareTo()method.
- Objects that implement the Comparable interface in Java can be used as keys in a SortedMap, such as TreeMap, or as elements in a SortedSet, such as TreeSet, without the need to specify a Comparator.
When to Use Comparable and Comparator Interfaces in Java
Use the Comparable interface when you want to define the natural ordering of objects and there is only one primary way to sort them. Since the sorting logic is implemented within the class itself using thecompareTo() method, it is ideal for value objects that have a single, well-defined ordering. Use the Comparator interface when you need multiple sorting orders for the same class or when you cannot modify the source code of the class. The sorting logic is implemented externally using the
Let us see coding example to see real implementation of these interfaces. This example will help you to understand it more clearly,
OUTPUT:--
******Before Sorting******
Name: Mahesh AGE: 26 SALARY: 10,000
Name: Satish AGE: 35 SALARY: 5,000
Name: Anil AGE: 41 SALARY: 6,500
Name: Hanamant AGE: 44 SALARY: 4,000
******After Comparable Sorting On Salary******
Name: Hanamant AGE: 44 SALARY: 4,000
Name: Satish AGE: 35 SALARY: 5,000
Name: Anil AGE: 41 SALARY: 6,500
Name: Mahesh AGE: 26 SALARY: 10,000
******After Comparator Sorting On Age******
Name: Mahesh AGE: 26 SALARY: 10,000
Name: Satish AGE: 35 SALARY: 5,000
Name: Anil AGE: 41 SALARY: 6,500
Name: Hanamant AGE: 44 SALARY: 4,000
Related Posts:--
1) String Interview Questions and Answers
2) What is the difference between SendRedirect() and Forward()?
3) Exception Handling Interview questions and answers
4) Difference between final,finalize and finally
5) Factory Design Pattern in Java
compare() method, allowing you to create different sorting criteria as needed.Sample Example of Comparable & Comparator interface:--
Let us see coding example to see real implementation of these interfaces. This example will help you to understand it more clearly,
package com.adnjavainterview; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class Employee implements Comparable<Employee> { private final String name; private int age; private int salary; public Employee(String name, int age, int salary) { this.name = name; this.age = age; this.salary = salary; } public int compareTo(Employee employee) { return salary - employee.salary; } public static class EmployeeAgeComparator implements Comparator<Employee> { public int compare(Employee emp1, Employee emp2) { return emp1.age - emp2.age; } } public String getName() { return name; } public int getAge() { return age; } public int getSalary() { return salary; } @Override public String toString() { return format("Name: {0} AGE: {1} SALARY : {2}", name, age, salary); } public static void main(String[] args) { List<Employee> employeeList = new ArrayList<Employee>(); employeeList.add(new Employee("Mahesh", 26, 10000)); employeeList.add(new Employee("Satish", 35, 5000)); employeeList.add(new Employee("Anil", 41, 6500)); employeeList.add(new Employee("Hanamant", 44, 4000)); System.out.println("******Before Sorting******"); printEmployees(employeeList); System.out.println("******After Comparable Sorting On Salary******"); Collections.sort(employeeList); printEmployees(employeeList); System.out.println("******After Comparator Sorting On Age******"); Collections.sort(employeeList, new Employee.EmployeeAgeComparator()); printEmployees(employeeList); } private static void printEmployees(List<Employee> employeeList) { for (Employee employee : employeeList) { System.out.println(employee); } } }
OUTPUT:--
******Before Sorting******
Name: Mahesh AGE: 26 SALARY: 10,000
Name: Satish AGE: 35 SALARY: 5,000
Name: Anil AGE: 41 SALARY: 6,500
Name: Hanamant AGE: 44 SALARY: 4,000
******After Comparable Sorting On Salary******
Name: Hanamant AGE: 44 SALARY: 4,000
Name: Satish AGE: 35 SALARY: 5,000
Name: Anil AGE: 41 SALARY: 6,500
Name: Mahesh AGE: 26 SALARY: 10,000
******After Comparator Sorting On Age******
Name: Mahesh AGE: 26 SALARY: 10,000
Name: Satish AGE: 35 SALARY: 5,000
Name: Anil AGE: 41 SALARY: 6,500
Name: Hanamant AGE: 44 SALARY: 4,000
Related Posts:--
1) String Interview Questions and Answers
2) What is the difference between SendRedirect() and Forward()?
3) Exception Handling Interview questions and answers
4) Difference between final,finalize and finally
5) Factory Design Pattern in Java
No comments:
Post a Comment