TreeSet 文档上写的是 TreeSet(Comparator<? super E> comparator)
比较器的泛型应该是任意类型或者其父类型,但是为什么<>中写Person类是,可以在TreeSet建立时比较Student和Worker类的对象?
虽然没有写<? super E>但是写Person也应该是比较Person本身或者其父类,为什么可以比较Person类的子类?那不跟<? extends E>的功能一样了吗?
另<? super E>什么时候用呢?
下面写个程序大家好明白我问问题的意思。- 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);
- }
- }
复制代码 |
|