Common mistakes and practice
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Most sorting bugs give no error at all: the list just comes out in the wrong order. They come from a few shortcuts, such as subtracting values, casting decimals to int, a compareTo that never says "equal", and sorting a list you should not change.
Mistake 1: subtraction in a comparator
Old tutorials write return a - b;. It works for marks and ages, so it looks fine. But an int holds only about ±2.1 billion. When the difference is bigger, it overflows: it wraps around to the opposite sign, and the comparator lies.
Example 1 · Mistake: a - b overflows
import java.util.ArrayList;import java.util.List;
public class OverflowDemo { public static void main(String[] args) { // account balances in paise: Rs. 2 crore, a Rs. 1.5 crore loan, zero List<Integer> balances = new ArrayList<>(); balances.add(2_000_000_000); balances.add(-1_500_000_000); balances.add(0);
balances.sort((a, b) -> a - b); System.out.println("With a - b: " + balances);
balances.sort((a, b) -> Integer.compare(a, b)); System.out.println("With Integer.compare: " + balances);
int diff = 2_000_000_000 - (-1_500_000_000); System.out.println("2000000000 - (-1500000000) = " + diff); }}With a - b: [2000000000, -1500000000, 0] With Integer.compare: [-1500000000, 0, 2000000000] 2000000000 - (-1500000000) = -794967296
What this code does
- An
intholds values only up to about 2.1 billion. 2 billion minus -1.5 billion should be 3.5 billion, but it wraps around to a negative number, so the comparator says the bigger balance comes first. Integer.compare(a, b)never subtracts, so it cannot overflow. Small values like marks hide the bug; it shows up later with money, ids or timestamps.
Money in paise, ids, timestamps and game scores easily reach that size. Use Integer.compare(a, b), Long.compare or comparingInt every time. They are just as short and always correct.
Predict the output
What does a - b sort to?
Read the program and pick what it prints.
Account balances in paise, sorted with subtraction.
Mistake 2: casting decimals to int
(int) (a.getCgpa() - b.getCgpa()) cuts off the decimal part, so 8.9 and 8.4 differ by (int) 0.5, which is 0. Every pair closer than 1 looks like a tie, and the stable sort leaves them unsorted.
Example 2 · Mistake: casting a double difference to int
import java.util.ArrayList;import java.util.Comparator;import java.util.List;
class Student { private String name; private double cgpa;
Student(String name, double cgpa) { this.name = name; this.cgpa = cgpa; }
double getCgpa() { return cgpa; }
@Override public String toString() { return name + " " + cgpa; }}
public class CgpaCastDemo { public static void main(String[] args) { List<Student> list = new ArrayList<>(); list.add(new Student("Aarav", 8.9)); list.add(new Student("Priya", 7.2)); list.add(new Student("Rohan", 8.4)); list.add(new Student("Kavya", 9.1));
list.sort((a, b) -> (int) (a.getCgpa() - b.getCgpa())); System.out.println("Cast to int: " + list);
list.sort(Comparator.comparingDouble(s -> s.getCgpa())); System.out.println("comparingDouble: " + list); }}Cast to int: [Priya 7.2, Aarav 8.9, Rohan 8.4, Kavya 9.1] comparingDouble: [Priya 7.2, Rohan 8.4, Aarav 8.9, Kavya 9.1]
What this code does
8.9 - 8.4is0.5, and(int) 0.5is0, so the comparator calls them a tie. Any two CGPAs less than 1 apart look equal, and the stable sort leaves them as they were.- For
doublekeys useDouble.compare(a, b)orComparator.comparingDouble(...). They compare the real values, decimals included.
Use Double.compare(a, b) or Comparator.comparingDouble(...). The same applies to float (Float.compare) and long (Long.compare).
Predict the output
What does the int cast sort to?
Read the program and pick what it prints.
CGPAs sorted by casting the difference to int.
Mistake 3: breaking the contract
A compareTo or compare must return 0 for equal items, opposite signs when the arguments are swapped, and the same answer every time. Shortcuts like return a >= b ? 1 : -1; break this.
Example 3 · Mistake: a compareTo that never returns 0
import java.util.ArrayList;import java.util.Collections;import java.util.List;
class Student implements Comparable<Student> { private String name; private int marks;
Student(String name, int marks) { this.name = name; this.marks = marks; }
@Override public int compareTo(Student o) { return this.marks >= o.marks ? 1 : -1; // BUG: never 0 }
@Override public String toString() { return name + " " + marks; }}
public class BrokenContractDemo { public static void main(String[] args) { Student kavya = new Student("Kavya", 85); Student rohan = new Student("Rohan", 85); System.out.println("kavya vs rohan: " + kavya.compareTo(rohan)); System.out.println("rohan vs kavya: " + rohan.compareTo(kavya)); System.out.println("kavya vs kavya: " + kavya.compareTo(kavya));
List<Student> list = new ArrayList<>(); list.add(new Student("Aarav", 72)); list.add(kavya); list.add(new Student("Divya", 91)); Collections.sort(list); System.out.println(list); System.out.println("Search for Kavya: " + Collections.binarySearch(list, kavya)); }}kavya vs rohan: 1 rohan vs kavya: 1 kavya vs kavya: 1 [Aarav 72, Kavya 85, Divya 91] Search for Kavya: -2
What this code does
- The contract says
a.compareTo(b)andb.compareTo(a)must have opposite signs, and an object must compare as 0 with itself. Here both directions say "after", and Kavya is not even equal to herself. - The sort happens to look right, but
binarySearchneeds a 0 to say "found", so it reports Kavya missing even though she is in the list. On large lists, broken comparators can also make the sort throwIllegalArgumentException: Comparison method violates its general contract!.
The damage is hard to spot. The sort may look right, but binarySearch cannot find items, sorted sets treat items wrongly, and on larger lists TimSort may throw IllegalArgumentException: Comparison method violates its general contract!.
Mistake 4: sorting the wrong list
List.of, List.copyOf and Collections.unmodifiableList cannot be sorted: they throw UnsupportedOperationException. A list passed into your method belongs to the caller, so sorting it changes their data too. In both cases, sort a copy: new ArrayList<>(list).
Example 4 · Mistake: sorting a list that cannot change
import java.util.List;
public class SortFixedListDemo { public static void main(String[] args) { List<String> toppers = List.of("Rohan", "Aarav", "Kavya"); toppers.sort(null); System.out.println(toppers); }}Exception in thread "main" java.lang.UnsupportedOperationException at java.base/java.util.ImmutableCollections.uoe(ImmutableCollections.java:142) at java.base/java.util.ImmutableCollections$AbstractImmutableList.sort(ImmutableCollections.java:261) at SortFixedListDemo.main(SortFixedListDemo.java:6)
What this code does
List.of(andList.copyOf) make unmodifiable lists. Sorting changes the order of the list, so it throwsUnsupportedOperationException.- Fix: sort a copy you own:
List<String> sorted = new ArrayList<>(toppers); sorted.sort(null);. The same fix protects a caller's list when your method only needs a sorted view.
Also remember that Collections.sort and list.sort return void, so List<String> s = Collections.sort(names); does not compile. And keep reversed() right after the key it should flip, not at the end of the chain.
Finish up
Mark complete & continue
Next: HashSet: no duplicates