• Post Reply Bookmark Topic Watch Topic
  • New Topic

Exception in adding values in treeset  RSS feed

 
Rajesh Santhanakrishnan
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I am trying to add few few objects to treeset, but it is giving me an exception "Exception in thread "main" java.lang.ClassCastException: demo.People cannot be cast to java.lang.Comparable"
Any idea on this? Below is the code snippet that I am trying.




 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

With a TreeSet, elements either have to be Comparable, or otherwise, you must provide a Comparator that can compare the elements. Without either, the TreeSet will not be able to sort the elements.

As for the error that you are seeing, you didn't provide a Comparator, so the TreeSet assumes that it is Comparable -- and throws an exception when the cast is attempted.

Henry
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!