为什么已经继承了Person. 编译器提示无法通过方法调用转换实际参数TreeSet<Student>.TreeSet<Worker>
转换为TreeSet<Person>,而将<Person> 改为<? extends Person> 却可以呢?
请大侠帮忙解答下
import java.util.*;
class Person
{
private String name;
Person(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
}
class Worker extends Person
{
Worker(String name)
{
super(name);
}
}
class Student extends Person
{
Student(String name)
{
super(name);
}
}
class GeneticDemo4
{
public static void main(String[] args)
{
TreeSet<Student> ts1 = new TreeSet<Student>(new comp());
ts1.add(new Student("hehe 1"));
ts1.add(new Student("hehe 3"));
ts1.add(new Student("hehe 24"));
ts1.add(new Student("hehe 79"));
ts1.add(new Student("hehe 40"));
printCll(ts1);
TreeSet<Worker> ts2 =new TreeSet<Worker>(new comp());
ts2.add(new Worker("he 1"));
ts2.add(new Worker("he 3"));
ts2.add(new Worker("he 9"));
ts2.add(new Worker("he 2"));
ts2.add(new Worker("he 5"));
printCll(ts2);
}
public static void printCll(TreeSet<Person> al)
{
Iterator<Person> it = al.iterator();
while (it.hasNext())
{
System.out.println(it.next().getName());
}
}
}
class comp implements Comparator<Person>
{
public int compare(Person p1,Person p2)
{
return p1.getName().compareTo(p2.getName());
}
}
|