Sorting

AP Computer Science A· difficulty 2/5

public class Item implements Comparable<Item> {
    private int v;
    public Item(int x) { v = x; }
    public int compareTo(Item o) {
        if (v < o.v) return -1;
        if (v > o.v) return 1;
        return 0;
    }
}
// Usage:
Item a = new Item(5);
Item b = new Item(5);
System.out.print(a.compareTo(b));

What is printed?

  • A

    -1

  • B

    5

  • C

    1

  • D

    0

    check_circle

Explanation

Equal values lead to compareTo returning 0. This is a valid (and safer) compareTo implementation that avoids overflow.

Want 10 more like this — adaptive to your weak spots?

Related questions