Java SE API
Comparator.compare(T, T)
Independent comparison policy. Zero may tie objects that are not equal; account for this when choosing sorted collection keys.
Formal Syntax & Structure
java syntaxjava
int compare(T first, T second)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| first | T | Object to compare. |
| second | 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)); }}