Why do i get classcast exception for this code

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){}
}

basically classcast exception is thrown when the class can not be casted with the proper form that is demanded.
1> in case of set the value should be mutually comparable. but unfortunately in you code you have not implemented comparable interface. you should implement that interface.
2> after using the comparable interface you should implement the method <class object 1>.compateTo(<class object 2>)
the above two process should exclude the exception from you code hopefully.
check out!

Similar Messages

Maybe you are looking for