Comparable.compareTo()
Defines the natural order of a class — used by sort() and TreeSet.
Available since: Java 1.2
Syntax
int compareTo(T o)Parameters
| Parameter | Type | Description |
|---|---|---|
| o | T | The object to compare this one with. |
Return value
intA negative number if this object is smaller, 0 if equal, a positive number if larger.
Examples
A record with a natural order by price:
record Product(String name, double price) implements Comparable<Product> {
@Override
public int compareTo(Product other) {
return Double.compare(price, other.price);
}
}
void main() {
var products = new ArrayList<>(List.of(
new Product("Tea", 4.5),
new Product("Coffee", 7.0),
new Product("Water", 1.2)));
Collections.sort(products);
products.forEach(p -> IO.println(p.name()));
}Output:
Water
Tea
CoffeeNotes
Use Integer.compare(a, b) and Double.compare(a, b) instead of subtracting a - b: subtracting large numbers overflows and gives the wrong sign. String, number wrappers and LocalDate already implement Comparable.
If you need several orders (by name, by price), the class implements one Comparable and the others are expressed with a Comparator.
See also
- Comparator.comparing() — Creates a comparator that compares objects by one key.
- String.compareTo() — Compares two strings in dictionary (lexicographic) order.
- implements — Lists the interfaces that a class implements.
- Arrays.sort() — Sorts an array in place — in ascending order or by a given comparator.
Related recipes
In the tutorial
- Sorting and comparators — Sorting collections in Java: natural order, reverse order, the Comparable interface, Comparator.comparing and sorting by several fields.