In Java, a.compareTo(b) compares the Integer object a with the Integerb. It returns a negative number if a is less, zero if both values are equal, and a positive number if a is greater. For Integer the result is exactly -1, 0, or 1.
This method makes Integer implement Comparable<Integer>, so lists and sorted collections know how to order numbers without any extra code.
An instance method of java.lang.Integer (since Java 1.2): call it on an Integer object. Integer lives in java.lang, so no import is needed.
Syntax
Call it on an Integer and pass another Integer or an int (Java boxes it).
Java
Integer a = 5;
int x = a.compareTo(9); // -1: 5 is less than 9
int y = a.compareTo(5); // 0
int z = a.compareTo(2); // 1
Call
What it does
a.compareTo(b)
Compare a with b.
b.compareTo(a)
The opposite direction gives the opposite sign.
Collections.sort(list)
Uses compareTo to put Integer elements in natural order.
Integer.compare(x, y)
The static version for primitive int values.
Test the sign of the result instead of comparing it to -1 or 1 when you write general code, because other classes return other numbers.
Library declarations
Java
// java.lang.Integer
public int compareTo(Integer anotherInteger)
// Required by Comparable<Integer>
Parameters
Parameter
Description
anotherInteger (Integer)
The object to compare with. It must not be null.
Return Value
Return Value
Description
-1
This value is numerically less than the argument.
0
Both values are equal.
1
This value is numerically greater than the argument.