Java Comparable compareTo() Method
Example
Let a Car class decide its own order (by year), and sort a list of cars:
import java.util.ArrayList;
import java.util.Collections;
public class Main {
static class Car implements Comparable<Car> {
String brand;
int year;
Car(String brand, int year) {
this.brand = brand;
this.year = year;
}
public int compareTo(Car other) {
return year - other.year;
}
public String toString() {
return brand + " " + year;
}
}
public static void main(String[] args) {
ArrayList<Car> myCars = new ArrayList<Car>();
myCars.add(new Car("BMW", 1999));
myCars.add(new Car("Honda", 2006));
myCars.add(new Car("Ford", 1970));
Collections.sort(myCars);
System.out.println(myCars);
}
}
Definition and Usage
The compareTo() method of the Comparable interface compares this object with another object of the same type. A class that implements Comparable writes this method to decide its own natural order (its default order).
It returns a negative number if this object should come first, a positive number if the other object should come first, and 0 if the order does not matter. You rarely call it yourself. Sorting methods, like Collections.sort(), call it for you.
Tip: To sort the same objects in another order, for example by brand, use a comparator, like comparing().
Syntax
public int compareTo(T o)
T refers to the data type of the objects, for example Car in class Car implements Comparable<Car>.
Parameter Values
| Parameter | Description |
|---|---|
| o | Required. The object to compare this object with. |
Technical Details
| Returns: | An int: a negative number if this object should come before o, a positive number if it should come after o, and 0 if the order does not matter. |
|---|
Related Pages
Java Advanced Sorting Tutorial
Java Lambda Expressions Tutorial
❮ Comparator Methods