Java comparable interface
Comparable is presents in Java.lang package
Comparable interface is used to sort the objects with natural ordering.
Comparable provides int CompareTo(T other ) method to sort elements.Here T means Type it can be Apple ,Cat any class.
Comparable interface compares “this” reference with the object specified.
Comparable affects the original class. The actual class is modified.
The Comparable interface in Java is used to compare objects of the same class.
It defines a single method, compareTo(), which takes an object of the same class as a parameter and returns an integer indicating the order of the two object.
why the same class ?
It makes the comparison method more meaningful. If the compareTo() method could compare objects of different classes,
it would be difficult to define a meaningful comparison method. For example, how would you compare a Cat object to a Dog object?
How it works?
compareTo() method in the Comparable interface always returns an integer indicating the order of the two objects.
What can it compare?
The compareTo() method can be used to compare various data types, including String, Double, and custom classes.
The returned integer can be:
A negative integer if the this object is less than the specified object
Zero if the this object is equal to the specified object
A positive integer if the this object is greater than the specified object
This allows the compareTo() method to be used to sort collections of objects, as well as to compare individual objects.
A sample code we can write to compare apples based on the weight.
public class Apple implements Comparable<Apple> {
/* When a class implements the Comparable interface,
the compareTo method is typically implemented within the class itself.
This method defines the natural ordering of instances of that class.*/
private String variety;
private Color color;
private int weight;
@Override
public int compareTo(Apple other) {
if (this.weight < other.weight) {
return -1;
}
if (this.weight == other.weight) {
return 0;
}
return 1;
}
}
However, there is an inbuilt method equal to above code.
@Override
public int compareTo(Apple other) {
return Integer.compare(this.weight, other.weight);
}
Here let’s look at an example of sorting apples based on its weight.
package com.comparableexample;
// Apple class implements the Comparable interface and type is Apple
public class Apple implements Comparable<Apple>{
String country;
int weight;
// Constructor to create an Apple
public Apple(String country, int weight) {
this.country = country;
this.weight = weight;
}
@Override // The compareTo method compares the weights of two apples for natural ordering (ascending order, from low to high weights)
public int compareTo(Apple other) {
return Integer.compare(this.weight,other.weight);
}
@Override // toString method to return the country
public String toString() {
return country + ": " + weight;
}
}
The class with the Main method
package com.comparableexample;
import java.util.Arrays;
public class AppleSortingByWeight {
public static void main(String[] args) {
// Array of apples with country and weight
Apple[] apples = {
new Apple("Australia", 50), // Creating a new Apple with country "Australia" and weight 50
new Apple("Canada", 100),
new Apple("USA", 75),
new Apple("China", 90)
};
// Sorting using Arrays.sort() method
Arrays.sort(apples);
// Displaying sorted apples
System.out.println("Sorted Apples:");
for (Apple apple : apples) {
System.out.println(apple);
}
}
}
A question?
so when called // Sorting using Arrays.sort() method
Arrays.sort(apples);
below line ger called.
public int compareTo(Apple other) {
return Integer.compare(this.weight,other.weight);
}
How are the two values that need to be compared are passed ? since compareTo method only allows one parameter?
The compareTo method is designed to compare the current object (this) with another object (other).
Current Object (this): In Java, when you’re inside an instance method of a class,
you can refer to the instance itself using the keyword this. In the context of the compareTo method within the Apple class:
When you use Arrays.sort(apples), the Arrays.sort method internally calls the compareTo method of the Apple class to determine the order of the elements in the array.
Here’s how it works:
The Arrays.sort method uses the natural ordering of the elements. In this case, it relies on the compareTo method of the Comparable interface.
When you call Arrays.sort(apples), the sort method internally uses the compareTo method for comparisons.
For each pair of elements (let’s say apples A and B), the compareTo method is called on the A object with B as an argument.
Within the compareTo method, this refers to the current object (in this case, apple A), and other refers to the object being compared (apple B).
Now, let’s assume that there are can be multiple apples from the same country. Also apples have colours like green, red , yellow. So based on the country and the colour can we sort them ?
package com.comparablemultiple;
class Apple implements Comparable<Apple> {
String country;
String color;
int weight;
public Apple(String country, String color, int weight) {
this.country = country;
this.color = color;
this.weight = weight;
}
@Override
public int compareTo(Apple other) {
// Compare by country, then by color, then by weight
int countryComparison = this.country.compareTo(other.country);
// If the result is 0, it means that the compared values are considered equal.
if (countryComparison == 0) {
int colorComparison = this.color.compareTo(other.color);
if (colorComparison == 0) {
return Integer.compare(this.weight, other.weight);
}
return colorComparison;
}
return countryComparison;
}
@Override
public String toString() {
return country + " - " + color + ": " + weight;
}
}
The class with the main method
package com.comparablemultiple;
import java.util.Arrays;
public class AppleSorting {
public static void main(String[] args) {
// Array of apples with country, color, and weight
Apple[] apples = {
new Apple("Australia", "red", 50),
new Apple("Canada", "red", 100),
new Apple("USA", "green", 75),
new Apple("China", "green", 90),
new Apple("USA", "green", 70),
new Apple("Australia", "red", 50),
new Apple("USA", "green", 75),
new Apple("Australia", "red", 66)
};
// Sorting using Arrays.sort() method
Arrays.sort(apples);
// Displaying sorted apples
System.out.println("Sorted Apples:");
for (Apple apple : apples) {
System.out.println(apple);
}
}
}
Can I use to compare two int values?
No, you cannot directly use the compareTo() method from the Comparable interface to compare two int values. The compareTo() method is designed to compare objects of the same class, and int is a primitive data type, not an object.
However, you can use the Integer class to wrap the int values and then compare them using the compareTo() method. The Integer class is a wrapper class for primitive int values. It provides various methods for working with int values, including the compareTo() method.
public class CompareIntValues {
public static void main(String[] args) {
int a = 50;
int b = 100;
Integer integerA = new Integer(a);
Integer integerB = new Integer(b);
int result = integerA.compareTo(integerB);
if (result < 0) {
System.out.println("a is less than b");
} else if (result == 0) {
System.out.println("a is equal to b");
} else {
System.out.println("a is greater than b");
}
}
}
A useful video and a reference-https://www.youtube.com/watch?v=swEvHhN9l8k&t=384s