File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question 10 Chapter 7 : K and B

 
jose chiramal
Ranch Hand
Posts: 266
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Exception in thread "main" java.lang.ClassCastException: java.lang.Object cannot be cast to java.lang.Comparable


I tried compiling the above prog but got this exception :

Exception in thread "main" java.lang.ClassCastException: java.lang.Object cannot be cast to java.lang.Comparable
 
Harpreet Singh janda
Ranch Hand
Posts: 317
Eclipse IDE
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You need to add object which implements the comparable interface of. This is the default implementation of the add method.
Below is the excerpt from API

 
Rahul Manikuntla
Greenhorn
Posts: 11
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, TreeSet is sorted collection and must have elements that implement compareTo() from interface Comparable. That is how TreeSet will know where to add() the new elements.
 
Rajeev Rnair
Ranch Hand
Posts: 308
Java Linux Oracle
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rahul Manikuntla wrote:Yes, TreeSet is sorted collection and must have elements that implement compareTo() from interface Comparable. That is how TreeSet will know where to add() the new elements.
Exactly! In

you are adding a String and an Object o. String, Wrappers, Date classes implement Comparable by default. But cannot add a plain "Object o" which hasn't implemented Comparable.
 
Ankit Garg
Sheriff
Posts: 9495
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is not necessary that the objects that we add to a TreeSet implement Comparable. If we use a Comparator, then we can add elements to the TreeSet which don't implement Comparable. Eg:-
The rule is, the elements that we add to the TreeSet must be comparable to each other...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic