泛型限定示例

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());
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值