• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Comparator

 
Ranch Hand
Posts: 186
Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


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
 
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Ranch Hand
Posts: 236
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Vijay Chandran
Ranch Hand
Posts: 186
Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Kindly excuse me for not posting the stack trace.

Anyway my doubt got cleared.

Thanks for your replies!!


Regards,
Vijay
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
So just to make it clear for everybody, you should have implemented Comparable instead of Comparator.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic