本帖最后由 xjandrew 于 2012-12-12 01:13 编辑
结果会抛异常- import java.util.*;
- public class TreesetTest
- {
- public static void main(String[] args)
- {
- //TreeSet<? extends Person> ts = new TreeSet<Student>();//执行这句的话,add方法报错,类型不匹配
- ts.<FONT color=red>add</FONT>(new Person("zhangsan",23));
- ts.<FONT color=red>add</FONT>(new Person("zhangsan",22));
- TreeSet<? super Student> ts = new TreeSet<Student>();//执行这句话,Person报错,类型转换异常(Person无法转成Student)
- ts.add((Student) new Person("zhangsan",23));
- ts.add((Student) new Person("zhangsan",22));
- ts.add(new Student("zhangsan",23,3));
- ts.add(new Student("zhangsan",22,2));
-
- }
- }
- class <FONT color=red>Person</FONT> implements Comparable<Student>
- {
- private String name;
- private int age;
-
- Person(String name,int age)
- {
- this.name = name;
- this.age = age;
- }
- public String getName()
- {
- return name;
- }
- public int getAge()
- {
- return age;
- }
-
- public int compareTo(Person p)
- {
- int num = this.name.compareTo(p.getName());
- if(num == 0)
- return new Integer(this.age).compareTo(new Integer(p.getAge()));
- return num;
-
- }
- @Override
- public int compareTo(Student o) //这里还必须留给子类重写
- {
- // TODO Auto-generated method stub
- return 0;
- }
- }
- class Student extends Person //implements Comparable<Student>加这句不行
- {
- private int nianji;
- Student(String name,int age,int nianji)
- {
- super(name,age);
- this.nianji = nianji;
- }
- public int compareTo(Student s)
- {
- int num = new Integer(this.nianji).compareTo(new Integer(s.getNianji()));
- return num;
- }
- public int getNianji()
- {
- return nianji;
- }
- }
- *
复制代码 |