问题代码:
import java.sql.Timestamp;
import java.util.Date;
public class T {
public static void main(String[] args) {
Object newObj = new Date(1999,9,10);
Object dbObj = new Timestamp(1);
[color=red] int compResult = ((Date)dbObj).compareTo((Date)newObj);[/color]
}
}
jdk1.5.06代码:
public int compareTo(java.util.Date o) {
return compareTo((Timestamp)o);
}
异常:
Exception in thread "main" java.lang.ClassCastException: java.util.Date
at java.sql.Timestamp.compareTo(Timestamp.java:474)
at com.test.T.main(T.java:10)
jdk1.5.16代码:
public int compareTo(java.util.Date o) {
if(o instanceof Timestamp) {
// When Timestamp instance compare it with a Timestamp
// Hence it is basically calling this.compareTo((Timestamp))o);
// Note typecasting is safe because o is instance of Timestamp
return compareTo((Timestamp)o);
} else {
// When Date doing a o.compareTo(this)
// will give wrong results.
Timestamp ts = new Timestamp(o.getTime());
return this.compareTo(ts);
}
}
import java.sql.Timestamp;
import java.util.Date;
public class T {
public static void main(String[] args) {
Object newObj = new Date(1999,9,10);
Object dbObj = new Timestamp(1);
[color=red] int compResult = ((Date)dbObj).compareTo((Date)newObj);[/color]
}
}
jdk1.5.06代码:
public int compareTo(java.util.Date o) {
return compareTo((Timestamp)o);
}
异常:
Exception in thread "main" java.lang.ClassCastException: java.util.Date
at java.sql.Timestamp.compareTo(Timestamp.java:474)
at com.test.T.main(T.java:10)
jdk1.5.16代码:
public int compareTo(java.util.Date o) {
if(o instanceof Timestamp) {
// When Timestamp instance compare it with a Timestamp
// Hence it is basically calling this.compareTo((Timestamp))o);
// Note typecasting is safe because o is instance of Timestamp
return compareTo((Timestamp)o);
} else {
// When Date doing a o.compareTo(this)
// will give wrong results.
Timestamp ts = new Timestamp(o.getTime());
return this.compareTo(ts);
}
}