本帖最后由 赵海洋 于 2013-4-2 14:19 编辑
- import java.util.*;
- class test1
- {
- public static void main(String[] args)
- {
- TreeSet<Student> ts = new TreeSet<Student>(new Comp());
- ts.add(new Student("abc1"));
- ts.add(new Student("abc2"));
- ts.add(new Student("abc3"));
- Iterator it = ts.iterator();
- while (it.hasNext())
- {
- System.out.println(it.next());
- }
- }
- }
- class Person
- {
- private String name;
- Person(String name)
- {
- this.name = name;
- }
- public String getName()
- {
- return name;
- }
- }
- class Student extends Person implements Comparable<Person>
- {
- Student(String name)
- {
- super(name);
- }
- public int compareTo(Person s)
- {
- return this.getName().compareTo(s.getName());
- }
- }
- class Comp implements Comparator<Person>
- {
- public int compare(Person s1,Person s2)
- {
- return s1.getName().compareTo(s2.getName());
- }
- }
复制代码 在以上代码中,添加的是Student类的东西,Student继承了Person,Comp是一个比较器,实现了Comparator接口,并重写了compare方法。添加子类元素,传递到比较器,类型是父类的,能够传进,此时这些 元素的类型还是子类的么?为什么这里没有写? extends Person或者? super Student也能成功运行?麻烦各位给解释一下具体运行流程~~~
|