Sorting

AP Computer Science A· difficulty 4/5

public class Card implements Comparable<Card> {
    private int rank;
    public Card(int r) { rank = r; }
    public int compareTo(Card other) {
        return rank - other.rank;
    }
    public int getRank() { return rank; }
}
// Usage:
Card a = new Card(5);
Card b = new Card(8);
int r = a.compareTo(b);
System.out.print(r < 0);

What is printed?

  • A

    false

  • B

    0

  • C

    true

    check_circle
  • D

    Compile error

Explanation

a.rank - b.rank = 5 - 8 = -3, which is less than 0, so r < 0 is true.

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

Related questions

AP Computer Science A · Sorting Practice Question | Acemy