Sorting

AP Computer Science A· difficulty 4/5

public class Pair implements Comparable<Pair> {
    private int a, b;
    public Pair(int x, int y) { a = x; b = y; }
    public int compareTo(Pair other) {
        if (this.a != other.a) return this.a - other.a;
        return this.b - other.b;
    }
    public int getA() { return a; }
    public int getB() { return b; }
}
// Usage:
Pair p = new Pair(2, 5);
Pair q = new Pair(2, 3);
System.out.print(p.compareTo(q) > 0);

What is printed?

  • A

    Compile error

  • B

    true

    check_circle
  • C

    false

  • D

    0

Explanation

a fields are equal (both 2), so the tie-breaker compares b: 5 - 3 = 2 > 0, so true.

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

Related questions