Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

why the output is classcastexception ?

 
kavitha satteli
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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){}
}
 
P Ventura
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Person is not comparable: if you change to this, all works

 
Madhukar Ojha
Ranch Hand
Posts: 71
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
TreeSet is a container which put objects in sorted order.
In order to sort data , object being added should be of type Comparable .
In class Person implements Comparable interface and implements its method.
When you add any new object , this method will be called for comparison .
 
Andry Dub
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This code will compile and run without exceptions:

import java.util.*;
public class Test1{
public static void main(String a[]){
Set s = new HashSet(); <--- guess why
s.add(new Person(20));
s.add(new Person(10));
System.out.println(s);
}
}
class Person{
Person(int i){}
}
[ November 13, 2007: Message edited by: Andry Dub ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic