Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Comparator

 
Vijay Chandran
Ranch Hand
Posts: 186
Java
  • Mark post as helpful
  • send pies
  • 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
 
Jeff Rummings
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • 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.
 
Paul Santa Maria
Ranch Hand
Posts: 236
  • Mark post as helpful
  • send pies
  • 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
  • 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
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15276
38
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So just to make it clear for everybody, you should have implemented Comparable instead of Comparator.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic