Comparable in Java — Learn About Comparable & Comparator Interfaces

Swatee Chand
Edureka
Published in
6 min readJul 9, 2019

--

Comparable in Java — Edureka

In the Java programming language, an interface is used to specify a behavior that classes must implement. Java world offers us two such interfaces Comparable and Comparator! Comparable in Java is used to sort the objects with natural ordering while Comparator is used to sort attributes of different objects. Let’s understand these interfaces through the medium of this article.

I have covered the following pointers which demonstrate comparable and comparator in Java:

  • What is Comparable in Java?
  • How to use the compareTo method?
  • Java Comparable example
  • What is Comparator in Java?
  • How to implement a Comparator?
  • Comparable v/s Comparator in Java

Now that we are clear with our agenda, let’s begin!

What is Comparable in Java?

As the name itself suggests, Comparable is an interface which defines a way to compare an object with other objects of the same type. It helps to sort the objects that have self-tendency to sort themselves, i.e., the objects must know how to order themselves. Eg: Roll number, age, salary. This interface is found in java.lang package and it contains only one method, i.e., compareTo(). Comparable is not capable of sorting the objects on its own, but the interface defines a method int compareTo() which is responsible for sorting.

Further, you must be thinking what is the compareTo method? Well, let me explain that to you!

What is the compareTo method and how it is used?

This method is used to compare the given object with the current object. The compareTo() method returns an int value. The value can be either positive, negative, or zero. So now we are well acquainted with the theoretical knowledge of Comparable interface in Java and compareTo method.

Let’s hop into understanding the implementation process. First, let’s see how to implement Comparable.

Java Comparable example

Below code depicts the usage of comparable in Java.

public class Student implements Comparable {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public int getAge() {
return this.age;
}
public String getName() {
return this.name;
}
@Override
public String toString() {
return "";
}
@Override
public int compareTo(Student per) {
if(this.age == per.age)
return 0;
else
return this.age > per.age ? 1 : -1;
}

public static void main(String[] args) {
Person e1 = new Person("Adam", 45);
Person e2 = new Person("Steve", 60);
int retval = e1.compareTo(e2);

switch(retval) {
case -1: {
System.out.println("The " + e2.getName() + " is older!");
break;
}

case 1: {
System.out.println("The " + e1.getName() + " is older!");
break;
}

default:
System.out.println("The two persons are of the same age!");

}
}
}

In the above example, I have created a class Student with two fields, name and age. Class Student is implementing the Comparable interface and overrides the compareTo method. This method sorts the instances of the Student class, based on their age.

Now that I have covered Comparable in Java, moving on I will talk about another interface i.e. Comparator in Java. Let’s move to understanding Comparator in Java!

What is Comparator in Java?

A Comparator interface is used to order the objects of a specific class. This interface is found in java.util package. It contains two methods;

  • compare(Object obj1,Object obj2)
  • equals(Object element).

The first method, compare(Object obj1,Object obj2) compares its two input arguments and showcase the output. It returns a negative integer, zero, or a positive integer to state whether the first argument is less than, equal to, or greater than the second.

The second method, equals(Object element), requires an Object as a parameter and shows if the input object is equal to the comparator. The method will return true, only if the mentioned object is also a Comparator. The order remains the same as that of the Comparator.

After attaining brief learning about Comparator in Java, it’s time to move a step ahead. Let me show you an example depicting Comparator in Java.

How to implement Comparator in Java

Here is an example of using Comparator in Java:

import java.util.Comparator;

public class School {
private int num_of_students;
private String name;
public Company(String name, int num_of_students) {
this.name = name;
this.num_of_students = num_of_students;
}
public int getNumOfStudents() {
return this.num_of_students;
}
public String getName() {
return this.name;
}
}
public class SortSchools implements Comparator {
@Override
public int compare(School sch1, School sch2) {
if(sch1.getNumOfStudents()== sch2.getNumOfStudents())
return 0;
else
return sch1.getNumOfStudents() > sch2.getNumOfStudents() ? 1 : -1;
}
public static void main(String[] args) {
School sch1 = new School("sch1", 20);
School sch2 = new School("sch2", 15);
SortSchools sortSch = new SortSchools();
int retval = sortSch.compare(sch1, sch2);
switch(retval) {
case -1: {
System.out.println("The " + sch2.getName() + " is bigger!");
break;
}
case 1: {
System.out.println("The " + sch1.getName() + " is bigger!");
break;
}
default:
System.out.println("The two schools are of the same size!");
}
}
}

Output:
The sch1 is bigger!

Well, no need to panic here. The above-written code is really easy to understand. Let’s go!

First, I created a class School that consists of the name and age of the students. After that, I created another class, SortSchools, in order to implement the Comparator interface which accomplishes the goal of imposing an order between instances of the first class named, School, according to the number of students.

After understanding about Comparator as well as Comparable in Java, let’s move towards our next topic.

Comparable v/s Comparator in Java

I hope the above-mentioned differences brought some clarity regarding the two concepts.

With this, we have reached towards the end of our article. Hope that the content turned out to be informative and imparted knowledge to your Java world. Stay tuned!

If you wish to check out more articles on the market’s most trending technologies like Artificial Intelligence, DevOps, Ethical Hacking, then you can refer to Edureka’s official site.

Do look out for other articles in this series which will explain the various other aspects of Java.

1. Object Oriented Programming

2. Inheritance in Java

3. Polymorphism in Java

4. Abstraction in Java

5. Java String

6. Java Array

7. Java Collections

8. Java Threads

9. Introduction to Java Servlets

10. Servlet and JSP Tutorial

11. Exception Handling in Java

12. Advanced Java Tutorial

13. Java Interview Questions

14. Java Programs

15. Kotlin vs Java

16. Dependency Injection Using Spring Boot

17. Java Tutorial

18. Top 10 Java frameworks

19. Java Reflection API

20. Top 30 Patterns in Java

21. Core Java Cheat Sheet

22. Socket Programming In Java

23. Java OOP Cheat Sheet

24. Annotations in Java

25. Library Management System Project in Java

26. Trees in Java

27. Machine Learning in Java

28. Top Data Structures & Algorithms in Java

29. Java Developer Skills

30. Top 55 Servlet Interview Questions

31. Top Java Projects

32. Java Strings Cheat Sheet

33. Nested Class in Java

34. Java Collections Interview Questions and Answers

35. How to Handle Deadlock in Java?

36. Top 50 Java Collections Interview Questions You Need to Know

37. What is the concept of String Pool in Java?

38. What is the difference between C, C++, and Java?

39. Palindrome in Java- How to check a number or string?

40. Top MVC Interview Questions and Answers You Need to Know

41. Top 10 Applications of Java Programming Language42. Deadlock in Java

43. Square and Square Root in Java

44. Typecasting in Java

45. Operators in Java and its Types

46. Destructor in Java

47. Binary Search in Java

48. MVC Architecture in Java

49. Hibernate Interview Questions And Answers

Originally published at https://www.edureka.co on July 9, 2019.

--

--