Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / May 2006

Tip: Looking for answers? Try searching our database.

java.lang.ClassCastException

Thread view: 
nash_rack1@yahoo.com - 01 May 2006 22:45 GMT
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.
Bjorn Abelli - 01 May 2006 23:02 GMT
<nash_rack1@yahoo.com> wrote...

> This piece of code works ok in JDK 1.4 and
> throws ClassCastException in
[quoted text clipped - 10 lines]
>
> 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


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.