
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){}
}
output: Exception in thread "main" java.lang.ClassCastException
plz explain the flow

TreeSet is a container which put objects in sorted order. In order to sort data , object being added should be of type Comparable.But the class Person does not implements the Comparable Interface, therefore the classcastexception occurs.
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 implements Comparable{
Person(int i){}
public int compareTo(Object arg0) {
return -1;
}
}
By implementing Comparable class and its method, you can remove the exception
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.