package test;
import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;
/**
* 泛型限定测试
* 上限限定如:<? extends T>
* 一般用法:用来定义函数,比如:<? extends T>定义为<? extends People>,限定T为People,
* 因此可以用来操作People的所有子类,但是只能用People的公用方法,而不能用子类的方法)。
* 下限限定,如<? super T>
* 一般用法,传一个特定的T(传入一个特定的T,T已固定),然后用T的方法,操作子类。如:构造函数
* TreeSet(Comparator<? super E> comparator) 用new TreeSet<People>(new Stucompar())
* 其中Stucompar为<People>,因此相当于固定了People,用People的方法操作子类。
*/
public class GenericTest {
public static void main(String[] args) {
TreeSet<People> ts = new TreeSet<People>(new Stucompar());
ts.add(new People("zhangsan"));
ts.add(new Student("lisi"));//定义People泛型,可以传Student,多态
sop(ts);
TreeSet<Student> ts1 = new TreeSet<Student>(new Stucompar());
ts1.add(new Student("zhaoliu"));
ts1.add(new Student("wangwu"));
sop(ts1);
}
/*传带泛型的ArrayList,ArrayList<Student>不能传入参数为(ArrayList<People> list)中,因为ArrayList<People> list
中list可以传People类型,可以传Student类型,可以传Worker类型。但是如果传入ArrayList<Student>,那么将不能传入Worker,
破坏了数据结构。*/
public static void sop(TreeSet<? extends People> ts){
for(Iterator<? extends People> it = ts.iterator(); it.hasNext();)
System.out.println(it.next());
}
}
class People{
String name;
public People(String name){
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "姓名:"+this.name;
}
}
class Student extends People{
public Student(String name){
super(name);
}
}
class Worker extends People{
public Worker(String name) {
super(name);
}
}
class Stucompar implements Comparator<People>{
@Override
public int compare(People p1, People p2) {
return p1.getName().compareTo(p2.getName());
}
}
泛型限定示例
最新推荐文章于 2021-02-27 05:23:17 发布