下列程序是毕老师讲的泛型的super E 下限应用。
class Comp implements Comparator<Person>这条语句我觉得还是 上限定,而不是 下限定。因为它
接收的是 Person类与Person类的子类对象,<Person>是不是应该改为<? extends Person>才是啊!
各路大神帮忙看看,帮忙梳理一下
import java.util.*;
class GenericDemo7
{
public static void main(String[] args)
{
TreeSet<Student> ts = new TreeSet<Student>(new Comp());
ts.add(new Student("abc03"));
ts.add(new Student("abc02"));
ts.add(new Student("abc06"));
ts.add(new Student("abc01"));
Iterator<Student> it = ts.iterator();
while(it.hasNext())
{
System.out.println(it.next().getName());
}
/**/
TreeSet<Worker> ts1 = new TreeSet<Worker>(new Comp());
ts1.add(new Worker("wabc--03"));
ts1.add(new Worker("wabc--02"));
ts1.add(new Worker("wabc--06"));
ts1.add(new Worker("wabc--01"));
Iterator<Worker> it1 = ts1.iterator();
while(it1.hasNext())
{
System.out.println(it1.next().getName());
}
}
}
class Comp implements Comparator<Person>
{
public int compare(Person p1,Person p2)
{
return p2.getName().compareTo(p1.getName());
}
}
class Person
{
private String name;
Person(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
public String toString()
{
return "person :"+name;
}
}
class Student extends Person
{
Student(String name)
{
super(name);
}
}
class Worker extends Person
{
Worker(String name)
{
super(name);
}
} |