JDK-6207898 : compareTo in java.util.Date, java.sql.Timestamp don't follow the contract
  • Type: Bug
  • Component: core-libs
  • Sub-Component: java.sql
  • Affected Version: 5.0
  • Priority: P3
  • Status: Closed
  • Resolution: Duplicate
  • OS: linux
  • CPU: x86
  • Submitted: 2004-12-13
  • Updated: 2011-02-16
  • Resolved: 2005-05-02
Related Reports
Duplicate :  
Description
FULL PRODUCT VERSION :
java version "1.5.0"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0-b64)
Java HotSpot(TM) Client VM (build 1.5.0-b64, mixed mode, sharing)


ADDITIONAL OS VERSION INFORMATION :
Linux sinaloa 2.4.19-4GB #1 Fri Sep 13 13:14:56 UTC 2002 i686 unknown


A DESCRIPTION OF THE PROBLEM :
The documentation of Comparable.compareTo(Comparable) specifies:
"x.compareTo(y) must throw an exception iff y.compareTo(x) throws an exception"
The following code demonstrates that on Java 1.5.0,
for x instanceof java.util.Date and y instanceof java.sql.Timestamp,
this requirement is not met.
One practical impact of this bug is, that before 1.5 it was possible to put Dates and Timestamps into the same SortedSet, while on 1.5 it is not.


STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
compile and run test code below

EXPECTED VERSUS ACTUAL BEHAVIOR :
EXPECTED -
expect no output
ACTUAL -
stack trace as below

ERROR MESSAGES/STACK TRACES THAT OCCUR :
Exception in thread "main" java.lang.ClassCastException: java.util.Date
        at java.sql.Timestamp.compareTo(Timestamp.java:474)
        at java.sql.Timestamp.compareTo(Timestamp.java:39)
        at Test.main(Test.java:7)


REPRODUCIBILITY :
This bug can be reproduced always.

---------- BEGIN SOURCE ----------
public class Test {
    public static void main(String[] args) {
        Comparable  x  = new java.util.Date();
        Comparable  y  = new java.sql.Timestamp(0l);

        x.compareTo(y); // succeeds
        y.compareTo(x); // fails (succeeds in version 1.3.1_08)
    }
}

---------- END SOURCE ----------

CUSTOMER SUBMITTED WORKAROUND :
A workaround is to specify a special Comparator that uses instanceof to reverse caller, callee and result if neccessary.
###@###.### 2004-12-13 22:54:41 GMT

Comments
EVALUATION This should be addressed as part of java.sql.Timestamp bug 5103041 ###@###.### 2005-04-15 18:12:27 GMT This bug will be fixed as part of 5103041. Please look into that bug for progress. This is to be fixed as part of mustang release. ###@###.### 2005-05-02 05:28:29 GMT
15-04-2005