Collections Framework
Comparable Interface
Analyze the Comparable interface natural sorting contract, compareTo implementation, and output constants.
Interview: Focuses on compareTo return values (-1, 0, 1), defining natural ordering, and natural sort integration.
The java.lang.Comparable interface is implemented by classes that have a natural ordering. It defines the single method compareTo(T o), which allows objects to be compared and sorted.
Natural Sort
Classes like String, Integer, and Date implement Comparable to define their default sorting order.
compareTo Contract
Returns a negative integer if this < o, zero if this == o, or a positive integer if this > o.
Consistency
The comparison result should align with equals(): (x.compareTo(y) == 0) == x.equals(y).
Implementing compareTo
When implementing compareTo, follow these mathematical properties:
- Symmetry: If
sgn(x.compareTo(y)) == -sgn(y.compareTo(x)), then reversing comparison parameters must flip the return sign. - Transitivity: If
x.compareTo(y) > 0andy.compareTo(z) > 0, thenx.compareTo(z) > 0must hold. - Substraction Overflow Danger: Avoid subtraction tricks like
this.id - o.id, which can overflow or underflow if negative integers are compared. UseInteger.compareinstead.
Common Pitfalls
- Integer Subtraction Overflow: Writing
this.score - o.scoreinside compareTo, causing buggy sorting behavior if values cross boundary limits. - Comparable inconsistent with equals: Creating a compareTo method that returns 0 for elements that are not equal according to equals. This can cause TreeSet to reject valid entries.
Best Practices
- Use static compare helpers: Always use utility compare methods (like
Integer.compareorDouble.compare) for comparing primitive fields. - Align with equals: Ensure that
compareToreturns 0 if and only ifequalsreturns true.
Interview-Relevant Information
Q1: What is the contract of compareTo(T o)?
Answer: It compares this object with the specified object o. It returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
Q2: Why can integer subtraction in compareTo cause bugs?
Answer: Subtraction (like this.val - o.val) can overflow if this.val is a large positive integer and o.val is a negative integer, reversing the sign of the return value and corrupting sort order.
Quick Checklist
Can you state the package containing Comparable, list the three return value signs of compareTo, and explain the integer overflow risk in subtraction? If yes, you understand Comparable interface.
Use Cases
Defining natural sort order for custom domain model collections.
Structuring key-sorting databases using comparable ID keys.
Common Mistakes
Using subtraction formulas inside compareTo, causing overflow bugs.
Creating comparison orders that do not align with equals.