Sorting

AP Computer Science A· difficulty 3/5

public class Score implements Comparable<Score> {
    private int v;
    public Score(int x) { v = x; }
    public int compareTo(Score o) { return o.v - this.v; }
    public int getV() { return v; }
}
// Usage:
ArrayList<Score> list = new ArrayList<Score>();
list.add(new Score(10));
list.add(new Score(30));
list.add(new Score(20));
// After Collections.sort(list):
System.out.print(list.get(0).getV());

What value is at index 0?

  • A

    20

  • B

    Sorting fails

  • C

    30

    check_circle
  • D

    10

Explanation

compareTo returns o.v - this.v, which reverses ordering. The largest value (30) is sorted first.

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

Related questions