黑马程序员技术交流社区

标题: 关于泛型限定之下限疑惑 [打印本页]

作者: 赵海洋    时间: 2013-4-1 17:16
标题: 关于泛型限定之下限疑惑
本帖最后由 赵海洋 于 2013-4-2 14:19 编辑
  1. import java.util.*;
  2. class test1
  3. {
  4.         public static void main(String[] args)
  5.         {
  6.                 TreeSet<Student> ts = new TreeSet<Student>(new Comp());
  7.                 ts.add(new Student("abc1"));
  8.                 ts.add(new Student("abc2"));
  9.                 ts.add(new Student("abc3"));

  10.                 Iterator it = ts.iterator();
  11.                 while (it.hasNext())
  12.                 {
  13.                         System.out.println(it.next());
  14.                 }
  15.         }
  16. }
  17. class Person
  18. {
  19.         private String name;
  20.         Person(String name)
  21.         {
  22.                 this.name = name;
  23.         }
  24.         public String getName()
  25.         {
  26.                 return name;
  27.         }
  28. }

  29. class Student extends Person implements Comparable<Person>
  30. {
  31.         Student(String name)
  32.         {
  33.                 super(name);
  34.         }
  35.         public int compareTo(Person s)
  36.         {
  37.                 return this.getName().compareTo(s.getName());
  38.         }
  39. }
  40. class Comp implements Comparator<Person>
  41. {
  42.         public int compare(Person s1,Person s2)
  43.         {
  44.                 return s1.getName().compareTo(s2.getName());
  45.         }
  46. }
复制代码
在以上代码中,添加的是Student类的东西,Student继承了Person,Comp是一个比较器,实现了Comparator接口,并重写了compare方法。添加子类元素,传递到比较器,类型是父类的,能够传进,此时这些 元素的类型还是子类的么?为什么这里没有写? extends Person或者? super Student也能成功运行?麻烦各位给解释一下具体运行流程~~~

作者: 齐静    时间: 2013-4-1 20:07
这应该是多态
TreeSet<Student> ts = new TreeSet<Student>(new Comp());
public int compare(Person s1,Person s2)  
执行时应该是 Person s1 = new Student();
Student 继承person 所以 student 可以使用person的方法即 s1.getName()
作者: 王川    时间: 2013-4-2 21:56
你在Comp的compare方法中添加System.out.println(s1.getClass().getName());这样一行代码,可以得到传递进来的对象的类型,发现,还是Student类




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2