Java SE API
Comparable.compareTo(T)
Natural comparison of this object with another; use the sign, not an exact magnitude.
Formal Syntax & Structure
java syntaxjava
int compareTo(T other)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| other | T | Object to compare. |
Return Value
int
Negative, zero or positive according to order.
Working Example
Example Snippetjava
import java.util.*;public class Main { record Job(String id, int priority) implements Comparable<Job> { public int compareTo(Job other) { int byId = id.compareTo(other.id); return byId != 0 ? byId : Integer.compare(priority, other.priority); } } static final class PriorityOrder implements Comparator<Job> { public int compare(Job a, Job b) { return Integer.compare(a.priority(), b.priority()); } } public static void main(String[] args) { Job a = new Job("A", 2); Job b = new Job("B", 2); Comparator<Job> byPriority = new PriorityOrder(); System.out.println(a.compareTo(b) < 0); System.out.println(byPriority.compare(a, b)); System.out.println(a.equals(b)); }}