Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Bud Tippins
Ranch Hand
Posts: 52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Pie
Posts: 20835
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
 
Matthew Brown
Bartender
Posts: 4549
8
Java Netbeans IDE Scala
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And if you don't want them sorted, just use a HashSet instead of a TreeSet.
 
Bud Tippins
Ranch Hand
Posts: 52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4549
8
Java Netbeans IDE Scala
  • 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 88
1
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks! That helped me too.
Thanks for the link Matthew Brown!
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic