File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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


Vijay Chandran
Ranch Hand

Joined: Jan 07, 2007
Posts: 186

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

Kindly provide me the solution

Jeff Rummings
Ranch Hand

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

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
at java.util.TreeMap.put(Unknown Source)
at java.util.TreeSet.add(Unknown Source)
at test.main(

The solution is here:

Paul M. Santa Maria, SCJP
Vijay Chandran
Ranch Hand

Joined: Jan 07, 2007
Posts: 186

Kindly excuse me for not posting the stack trace.

Anyway my doubt got cleared.

Thanks for your replies!!

Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15081

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 8 API documentation
I agree. Here's the link:
subject: Comparator
It's not a secret anymore!