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
- Dcheck_circle
20
Explanation
a.price - b.price = 50 - 30 = 20. compareTo returns this difference, so 20 is printed (positive means a > b).