黑马程序员技术交流社区
标题:
关于泛型限定之下限疑惑
[打印本页]
作者:
赵海洋
时间:
2013-4-1 17:16
标题:
关于泛型限定之下限疑惑
本帖最后由 赵海洋 于 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也能成功运行?麻烦各位给解释一下具体运行流程~~~
作者:
齐静
时间:
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