Java Comparable Interface
Last Updated :
17 Dec, 2024
The Comparable interface in Java is used to define the natural ordering of objects for a user-defined class. It is part of the java.lang package and it provides a compareTo() method to compare instances of the class. A class has to implement a Comparable interface to define its natural ordering.
Example 1: Here, we will use the Comparable interface to sort integers.
Java
import java.util.*;
class Number implements Comparable<Number> {
int v; // Value of the number
// Constructor
public Number(int v) {
this.v = v;
}
// toString() for displaying the number
@Override
public String toString() {
return String.valueOf(v);
}
// compareTo() method to
// define sorting logic
@Override
public int compareTo(Number o) {
// Ascending order
return this.v - o.v;
}
public static void main(String[] args) {
// Create an array of Number objects
Number[] n = { new Number(4), new Number(1),
new Number(7), new Number(2) };
System.out.println("Before Sorting: "
+ Arrays.toString(n));
// Sort the array
Arrays.sort(n);
// Display numbers after sorting
System.out.println("After Sorting: " + Arrays.toString(n));
}
}
OutputBefore Sorting: [4, 1, 7, 2]
After Sorting: [1, 2, 4, 7]
Explanation: In the above example, the compareTo() method is overridden to define the ascending order logic by comparing the v fields of Number objects. Then the Arrays.sort() method sorts the array by using this logic.
Declaration of Comparable Interface
public interface Comparable<T> {
int compareTo(T obj);
}
where, T is the type of object which to be compared.
- It compares the current object with the specified object.
- It returns:
- Negative, if currentObj < specifiedObj.
- Zero, if currentObj == specifiedObj.
- Positive, if currentObj > specifiedobj.
Use of Comparable Interface
- In this method, we are going to implement the Comparable interface from java.lang Package in the Pair class.
- The Comparable interface contains the method compareTo to decide the order of the elements.
- Override the compareTo method in the Pair class.
- Create an array of Pairs and populate the array.
- Use the Arrays.sort() function to sort the array.
Example 2: Sorting Pairs with String and Integer Fields
Given an array of Pairs consisting of two fields of type string and integer. Now, we have to sort the array in ascending Lexicographical order and if two strings are the same, sort it based on their integer value.
Java
import java.util.*;
class Pair implements Comparable<Pair> {
String s; // String
int v; // Integer
// Constructor
public Pair(String s, int v) {
this.s = s;
this.v = v;
}
// toString() method for
// displaying the Pair
@Override
public String toString() {
return "(" + s + ", " + v + ")";
}
// compareTo() method for
// comparison logic
@Override
public int compareTo(Pair p) {
// Compare based on the string field
// (lexicographical order)
if (this.s.compareTo(p.s) != 0) {
return this.s.compareTo(p.s);
}
// If strings are the same,
// compare based on the integer value
return this.v - p.v;
}
public static void main(String[] args) {
// Create an array of
// Pair objects
Pair[] p = {
new Pair("abc", 3),
new Pair("a", 4),
new Pair("bc", 5),
new Pair("a", 2)
};
System.out.println("Before Sorting:");
for (Pair p1 : p) {
System.out.println(p1);
}
// Sort the array of pairs
Arrays.sort(p);
System.out.println("\nAfter Sorting:");
for (Pair p1 : p) {
System.out.println(p1);
}
}
}
OutputBefore Sorting:
(abc, 3)
(a, 4)
(bc, 5)
(a, 2)
After Sorting:
(a, 2)
(a, 4)
(abc, 3)
(bc, 5)
Note: if two strings are the same then the comparison is done based on the value.
Example 3: Sorting Pairs with First and Last Names
Given an array of Pairs consisting of two strings with first and last names. Now, we have to sort the array in ascending Lexicographical order of the first name and if two strings are the same sort it based on their last name.
Java
import java.util.*;
class Pair implements Comparable<Pair> {
String f; // First name
String l; // Last name
// Constructor
public Pair(String f, String l) {
this.f = f;
this.l = l;
}
// toString() method
// for displaying the Pair
@Override
public String toString() {
return "(" + f + ", " + l + ")";
}
// compareTo method for
// comparison logic
@Override
public int compareTo(Pair p) {
// Compare based on the first name
// (lexicographical order)
if (this.f.compareTo(p.f) != 0) {
return this.f.compareTo(p.f);
}
// If first names are the same,
// compare based on the last name
return this.l.compareTo(p.l);
}
public static void main(String[] args) {
// Create an array of Pair objects
Pair[] p = {
new Pair("raj", "kashup"),
new Pair("rahul", "singh"),
new Pair("reshmi", "dubey"),
};
System.out.println("Before Sorting:");
for (Pair p1 : p) {
System.out.println(p1);
}
// Sort the array of pairs
Arrays.sort(p);
System.out.println("\nAfter Sorting:");
for (Pair p1 : p) {
System.out.println(p1);
}
}
}
OutputBefore Sorting:
(raj, kashup)
(rahul, singh)
(reshmi, dubey)
After Sorting:
(rahul, singh)
(raj, kashup)
(reshmi, dubey)
Comparable interface
Comparable Interface in Java with Examples
Similar Reads
Cloneable Interface in Java The Java.lang.Cloneable interface is a marker interface. It was introduced in JDK 1.0. There is a method clone() in the Object class. Cloneable interface is implemented by a class to make Object.clone() method valid thereby making field-for-field copy. This interface allows the implementing class to
4 min read
Java Functional Interfaces A functional interface in Java is an interface that contains only one abstract method. Functional interfaces can have multiple default or static methods, but only one abstract method. Runnable, ActionListener, and Comparator are common examples of Java functional interfaces. From Java 8 onwards, lam
7 min read
Java Interface An Interface in Java programming language is defined as an abstract type used to specify the behaviour of a class. An interface in Java is a blueprint of a behaviour. A Java interface contains static constants and abstract methods. Key Properties of Interface:The interface in Java is a mechanism to
12 min read
Collection Interface in Java The Collection interface in Java is a core member of the Java Collections Framework located in the java.util package. It is one of the root interfaces of the Java Collection Hierarchy. The Collection interface is not directly implemented by any class. Instead, it is implemented indirectly through it
6 min read
Externalizable interface in Java Externalization serves the purpose of custom Serialization, where we can decide what to store in stream.Externalizable interface present in java.io, is used for Externalization which extends Serializable interface. It consist of two methods which we have to override to write/read object into/from st
3 min read
Java Class vs Interfaces In Java, the difference between a class and an interface is syntactically similar; both contain methods and variables, but they are different in many aspects. The main difference is, A class defines the state of behaviour of objects.An interface defines the methods that a class must implement.Class
5 min read