本帖最后由 贾联国 于 2012-4-26 14:48 编辑
我觉得应该抛ClassCastException ,TreeSet中的自然排序必须是里面的元素满足comparable接口才行,而子类和父类的compareTo方法不一样,就不能进行自然排序
我自己写了个程序 没有写泛型(其实就是偷懒,把以前的程序直接贴上来了 连改都没改,很多都是没用的 见谅!^_^) 亲自测试是会抛异常的
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
- {
- private String name;
- private int age;
- Person (String name ,int age)
- {
- this.name=name;
- this.age= age;
- }
- public int compareTo(Object obj)
- {
- if(!(obj instanceof Student))
- throw new RuntimeException("bushi");
- Person p= (Person) obj;
- return this.name.compareTo(p.name);
- }
- }
复制代码 |