Exception in thread "main" java.lang.ClassCastException: Student cannot be cast
to Person
at Person.compareTo(TreeSetDemo.java:58)
at java.util.TreeMap.put(TreeMap.java:560)
at java.util.TreeSet.add(TreeSet.java:255)
at TreeSetDemo.main(TreeSetDemo.java:9)
import java.util.*;
class TreeSetDemo
{
public static void main(String[] args)
{
TreeSet ts = new TreeSet();
ts.add(new Student("lisi1",31));
ts.add(new Student("lisi2",32));
ts.add(new Person("lisi3",33));
ts.add(new Person("lisi4",34));
Iterator it= ts.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
}
}
class Student implements Comparable
{
private String name;
private int age;
Student () {}
Student (String name ,int age)
{
this.name=name;
this.age= age;
}
public int compareTo(Object obj)
{
if(!(obj instanceof Student))
throw new RuntimeException("bushi");
Student s= (Student) obj;
if(this.age>s.age)
return 1;
if(this.age==s.age)
return 0;
return -1;
}
}
class Person extends Student implements Comparable