Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Integer.compare: compare int values and sort by ID

Use `Integer.compare` to compare two signed `int` values or sort items by ascending ID without relying on subtraction that can overflow.

Version: Java SE 21

Syntax

public static int compare(int x, int y)

Integer.compare(x, y) is a static method of java.lang.Integer, available since Java 7. It takes two primitive int values and compares them as signed numbers. It returns a negative value when x < y, 0 when x == y, and a positive value when x > y. It does not return the difference. Test the sign rather than assuming a nonzero result is exactly -1 or 1.

To sort items by ascending int ID, use (a, b) -> Integer.compare(a.id(), b.id()) as the comparator. A result of 0 means the IDs are equal, not necessarily that the objects are equal. Don't replace the call with a.id() - b.id(): the difference can fall outside the int range, and overflow can give it the wrong sign without throwing an exception.

Integer.compareUnsigned(x, y) interprets the same bits as unsigned values. By contrast, compareTo(Integer) is an instance method on the Integer wrapper and uses signed ordering. An Integer argument passed to Integer.compare is unboxed to int; if it is null, unboxing throws NullPointerException before the method is called.

Examples

import java.util.ArrayList;
import java.util.List;

public class Main {
    record Item(int id) {}

    public static void main(String[] args) {
        int low = Integer.MIN_VALUE;
        int high = 1;
        System.out.println("compare < 0: " + (Integer.compare(low, high) < 0));
        System.out.println("low - high: " + (low - high));

        var items = new ArrayList<>(List.of(new Item(high), new Item(low), new Item(0)));
        items.sort((a, b) -> Integer.compare(a.id(), b.id()));
        System.out.println(items.stream().map(Item::id).toList());
    }
}

Result

compare < 0: true
low - high: 2147483647
[-2147483648, 0, 1]

`Integer.MIN_VALUE` is less than `1`, so the `compare < 0` test prints `true`. Subtraction overflows to the positive value `2147483647`, but the comparator still sorts the IDs in ascending order.

Related lessons

  • Java · Lesson 5 · Advanced · Version: 2
  • Java · Lesson 5 · Intermediate · Version: 2

Sources