Package relations: + java.lang + - java.lang.Comparable<T>
Parameter type:
T
- the type of objects that this object may be compared to
This interface is a member of Java Collections Framework.
Comparable interface is used to define natural ordering for objects of a class, it allows objects of the same type to be compared with each other. This interface contains only one abstract method named compareTo(Object)
.
Lists or arrays that implement Comparable
interface can be sorted using collections like ArrayList
or arrays through utility methods like Collections.sort()
or Arrays.sort()
.
compareTo()
The only method in comparable interface is the compareTo()
, which you need to implement in your class.
int compareTo(T o);
The method compares the current object and the parameter object for order. It returns:
- A negative integer if the current object is less than the specified object.
- Zero if the current object is equal to the specified object.
- A positive integer if the current object is greater than the specified object.
Example
public class Person implements Comparable<Person> {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public int compareTo(Person other) {
return Integer.compare(this.age, other.age);
}
@Override
public String toString() {
return name + " (" + age + ")";
}
}
Here we compare the Person
object based on the person’s age. Since age is integer value, we can directly use the Integer
class compareTo()
method because Integer
class implements the Comparable
interface (learn more about integer in Integer Class).
You can also define your own logic for object comparison:
@Override
public int compareTo(Person other) {
if (this.age < other.age) {
return -1;
} else if (this.age > other.age) {
return 1;
} else {
return 0;
}
}
Sorting
With the Person
class implementing the Comparable
interface from the previous example, you can now sort a list of Person
objects by their age using collections sort method from Java Collections
class.
import java.util.ArrayList;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
ArrayList<Person> people = new ArrayList<>();
people.add(new Person("Alice", 30));
people.add(new Person("Bob", 25));
people.add(new Person("Charlie", 35));
Collections.sort(people);
for (Person person : people) {
System.out.println(person);
}
}
}
Bob (25)
Alice (30)
Charlie (35)
Back to parent page: Java Standard Edition (Java SE) and Java Programming
Web_and_App_Development Programming_Languages Java Comparable Natural_Ordering Collections
Reference: