Comparison Method Violates Its General Contract! (Part 1)
summary
Explains why Java sorting sometimes throws "comparison method violates its general contract!" by showing concrete buggy comparators: Integer overflow via subtraction causes wrong signs, boxed Integers accidentally use reference equality instead of value equality, and IEEE floating point produces NaN compares false to everything so naive <, ==, > logic returns equals. Uses a logging wrapper comparator to replay comparisons, and recommends Integer.compare / Double.compare or natural order to get correct, predictable sorting.
AI-written summary · about
chapters (15)
- 0:00Introduction
- 0:43Title
- 3:13Integers
- 5:40Comparator
- 7:14Illegal argument exception
- 8:02Demo
- 8:16Run
- 8:40Writing a comparator
- 9:33The problem
- 10:30Wrapper comparator
- 13:05Relational comparator example
- 14:23Logging comparator example
- 18:36Checking the results
- 23:38Recap
- 26:03Comparator vs Comparable
related talks
47mHow the JVM Optimizes Generic Code - A Deep Dive
16m8 Java quirks in 16 minutes
28m11 Crazy Things I Didn't Know You Could Do With Java Until I Got...
50mModern Java Puzzlers
48mCollections.compare(JDK, Eclipse, Guava, Apache...);
56mJava Sucks (So C# Didn't Have To)
49mJava Collections Puzzlers
54mJava Puzzlers NG: The strange, the bizarre, and the wonderful
