aspose file tools*
The moose likes Beginning Java and the fly likes testtree.Book cannot be cast to java.lang.Comparable Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "testtree.Book cannot be cast to java.lang.Comparable" Watch "testtree.Book cannot be cast to java.lang.Comparable" New topic
Author

testtree.Book cannot be cast to java.lang.Comparable

Bud Tippins
Ranch Hand

Joined: Jan 28, 2011
Posts: 52
I'm getting an error in this code that says "Exception in thread "main" java.lang.ClassCastException: testtree.Book cannot be cast to java.lang.Comparable".

I'm running this in netBeans. What do I need to do to correct the code?

Thank you.

Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18995
    
  40


TreeSet sorts its elements. And there are two ways for you to help it with that. You can provide a Comparator when constructing the TreeSet. Or you can make the elements Comparable.

If you don't provide either, that is the exception that you will get from the TreeSet.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4467
    
    8

And if you don't want them sorted, just use a HashSet instead of a TreeSet.
Bud Tippins
Ranch Hand

Joined: Jan 28, 2011
Posts: 52
Henry, Thanks for your help. Can you show me what the code would look like if I provided a Comparator when constructing the TreeSet? Thank you.
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4467
    
    8

The important thing to ask when sorting objects is "does this class have a natural ordering". In other words, is there a sensible, default ordering that you'd want to use in the majority of case? If so, the best approach is to make the class implement Comparable. In this case, presumably you want to sort alphabetically by title? Then you can do this:
If you've done that, the TreeSet will just work as you want it.

If the class doesn't have a natural ordering, or if you don't want to use the natural ordering in this particular case, then that's when you need a Comparator. The code for creating the TreeSet with a Comparator is dead simple - there's a constructor that takes a Comparator as an argument: To create the comparator, just implement Comparator<Book>. The Java tutorials have a section giving more detail on all this at http://download.oracle.com/javase/tutorial/collections/interfaces/order.html.

Ashish Ramteke
Ranch Hand

Joined: Oct 24, 2012
Posts: 86
    
    1
Thanks! That helped me too.
Thanks for the link Matthew Brown!


Good day..! :-)
 
 
subject: testtree.Book cannot be cast to java.lang.Comparable