wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Comparator Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Comparator" Watch "Comparator" New topic
Author

Comparator

Vijay Chandran
Ranch Hand

Joined: Jan 07, 2007
Posts: 178


Dear friends,
This code is throwing a ClassCastException. I can't figure out why the exception is thrown.

Kindly provide me the solution

Regards,
Vijay
Jeff Rummings
Ranch Hand

Joined: Dec 20, 2007
Posts: 42
Your answer is in the javadocs:

Throws:
ClassCastException - if the specified object cannot be compared with the elements currently in the set.


You implemented the comparator but haven't provided it to the set.
Paul Santa Maria
Ranch Hand

Joined: Feb 24, 2004
Posts: 236
Hi -

There are several problems with the code...
... including the fact that you're not initializing testNumber
... which will cause all values you insert to compare as "=="
... which won't work with a "Set" (where all values must be unique...)

But the real problem is shown in this traceback (which you probably should have cut/pasted along with the code):
C:\temp>java test
Exception in thread "main" java.lang.ClassCastException: test cannot be cast to
java.lang.Comparable
at java.util.TreeMap.put(Unknown Source)
at java.util.TreeSet.add(Unknown Source)
at test.main(test.java:10)


The solution is here:
http://blog.tmro.net/2007/08/silly-classcastexception-in-java.html


Paul M. Santa Maria, SCJP
Vijay Chandran
Ranch Hand

Joined: Jan 07, 2007
Posts: 178
Kindly excuse me for not posting the stack trace.

Anyway my doubt got cleared.

Thanks for your replies!!


Regards,
Vijay
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14114
    
  16

So just to make it clear for everybody, you should have implemented Comparable instead of Comparator.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Comparator