public class Item implements Comparable<Item> {
private int v;
public Item(int x) { v = x; }
public int compareTo(Item o) { return v - o.v; }
public int getV() { return v; }
}
// Usage (assume sort puts smallest first):
ArrayList<Item> list = new ArrayList<Item>();
list.add(new Item(3));
list.add(new Item(1));
list.add(new Item(2));
// After Collections.sort(list):
// Print first element's value:What value is at index 0 after sorting?
- A
3
- Bcheck_circle
1
- C
2
- D
Sorting fails
Explanation
Collections.sort uses compareTo. With compareTo returning v - o.v, the natural order is ascending. The smallest value (1) ends up at index 0.