Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Class CAst Exception

 
ramya ray
Ranch Hand
Posts: 101
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It will be great help if some one please explain why the below code throwing Class Cast Exception:

import java.util.*;
public class Test1{
public static void main(String a[]){
Set s = new TreeSet();
s.add(new Person(20));
s.add(new Person(10));
System.out.println(s);
}
}
class Person{
Person(int i){}
}

..
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A TreeSet requires that either the elements you insert into have to be mutually comparable, i.e. the class definition implements the Comparable interface, or that you create the TreeSet with a Comparator that specifies how two objects in the set will be compared.
 
ramya ray
Ranch Hand
Posts: 101
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Keith ..i got it.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic