java.lang.ClassCastException

N

nash_rack1

This piece of code works ok in JDK 1.4 and throws ClassCastException in
1.5 on the line with compareTo call:

java.sql.Date d1 = new java.sql.Date(new java.util.Date().getTime());
java.sql.Timestamp d2 = new java.sql.Timestamp(new
java.util.Date().getTime());

java.util.Date ud1 = d1;
java.util.Date ud2 = d2;

int diff = ud2.compareTo(ud1);

Is this correct behavior in 1.5 or a bug? How can I make it use the
compareTo method in java.util.Date?

Nash.
 
B

Bjorn Abelli

This piece of code works ok in JDK 1.4 and
throws ClassCastException in
1.5 on the line with compareTo call:

java.sql.Date d1 = new java.sql.Date(new java.util.Date().getTime());
java.sql.Timestamp d2 = new java.sql.Timestamp(new
java.util.Date().getTime());

java.util.Date ud1 = d1;
java.util.Date ud2 = d2;

int diff = ud2.compareTo(ud1);

Is this correct behavior in 1.5 or a bug?

According to the API, that's the correct behavior since 1.5:
-------------------------------------
public int compareTo(Date o)
Compares this Timestamp object to the given Date, which must be a Timestamp
object. If the argument is not a Timestamp object, this method throws a
ClassCastException object. (Timestamp objects are comparable only to other
Timestamp objects.)
-------------------------------------
The explanation for this can be read at the introduction to the Timestamp
class:

/.../
Due to the differences between the Timestamp class and the java.util.Date
class mentioned above, it is recommended that code not view Timestamp values
generically as an instance of java.util.Date. The inheritance relationship
between Timestamp and java.util.Date really denotes implementation
inheritance, and not type inheritance.
/.../

However, when I tried it in 1.6 it *didn't* complain as it should...
How can I make it use the
compareTo method in java.util.Date?

It depends, but maybe something like this:

java.util.Date ud1 =
new java.util.Date( d1.getTime() );

java.util.Date ud2 =
new java.util.Date( d2.getTime() );


// Bjorn A




Inviato da X-Privat.Org - Registrazione gratuita http://www.x-privat.org/join.php
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,734
Messages
2,569,441
Members
44,832
Latest member
GlennSmall

Latest Threads

Top