aspose file tools*
The moose likes Beginning Java and the fly likes casting problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "casting problem" Watch "casting problem" New topic
Author

casting problem

K. Tsang
Bartender

Joined: Sep 13, 2007
Posts: 2517
    
    8

Hello all I have the below casting problem in my servlet program for stock trading system:
"java.lang.ClassCastException: trade.equity.XXXEquity cannot be cast to java.lang.Comparable"

The XXXEquity is a subclass of Equity, code looks like:



In servlet program parse URL content and add content to some set call it equitySet. In servlet I did something like:


equityBean class has addEquity method that looks like:


I don't know whether it is the compareTo method inside compare method of Equity class or simply with the line

in my servlet or something else that is causing the error.
Also do I really need to implement the Comparator interface in XXXEquity?

Please help.
[ July 11, 2008: Message edited by: K. Tsang ]

K. Tsang JavaRanch SCJP5 SCJD/OCM-JD OCPJP7 OCPWCD5 OCPBCD5
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39409
    
  28
The error message with your Exception tells you what you need to know.

Whichever object you have as equityTicker (BTW: why are you using direct access to a field?) does not implement the Comparable<T> interface and therefore does not have a compareTo(T t) method.
You might have a spelling error that you are implementing Comparator instead of Comparable<T>.

I cannot see an explicit cast operator in any of the code you have quoted, so you have probably not yet found the line where the exception took place.

BTW: Did you post your code with ctrl-c ctrl-v? There is a misprint in the fully-qualified name of Comparator, which would cause a compiler error.
K. Tsang
Bartender

Joined: Sep 13, 2007
Posts: 2517
    
    8

I fixed the problem by changing the Comparator to Comparable.

I also wonder why Comparator wouldn't work for sets? since both return an int. Does anyone know if the Set interface implements the Comparable interface inside its code that no one know about?
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39409
    
  28
Sets don't have a "natural ordering," so there is no point in them implementing Comparable.

And there is nothing implemented inside an interface, so no they don't. Interface methods are always implemented as public, anyway.
 
 
subject: casting problem