Sorting

AP Computer Science A· difficulty 3/5

public class Item implements Comparable<Item> {
    private int price;
    public Item(int p) { price = p; }
    public int compareTo(Item other) {
        return this.price - other.price;
    }
}
// Usage:
Item a = new Item(50);
Item b = new Item(30);
System.out.print(a.compareTo(b));

What is printed?

  • A

    0

  • B

    -20

  • C

    1

  • D

    20

    check_circle

Explanation

a.price - b.price = 50 - 30 = 20. compareTo returns this difference, so 20 is printed (positive means a > b).

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

Related questions