06-泛型

  • 类型安全:让集合只能添加指定数据类型的数据。

泛型类

public class Test {
    public static void main(String[] args) {
        A<Integer> a = new A<>();
        a.setKey(1);
        System.out.println(a.getKey());
    }
}

class A<T>{
    private T key;
    public void setKey(T key){
        this.key = key;
    }
    public T getKey(){
        return this.key;
    }
}

泛型接口

public class Test1 {
    public static void main(String[] args) {
        B1<Integer> b1 = new B1<>();
        B1<String> b11 = new B1<>();
        B2 b2 = new B2();
    }
}

interface IB<T>{
    T test(T t);
}
/*
如果实现接口时没有指定接口泛型的具体数据类型,需要将泛型的声明也一起加入类中。
 */
class B1<T> implements IB<T>{

    @Override
    public T test(T t) {
        return null;
    }
}
class B2 implements IB<String>{

    @Override
    public String test(String s) {
        return null;
    }
}

泛型方法

  • 泛型方法,在调用之前没有固定的数据类型,在调用时,传入的参数是什么类型,就会把泛型改成什么类型。
class  cc{
    //无返回值的泛型方法,<T>定义泛型
    public <T> void test(T s){
        T t = s;
    }
    //有返回值的泛型方法
    public <T> T test1(T s){
        return s;
    }
    
}

泛型通配符

  • 不确定集合中的元素具体的数据类,使用?表示所有类型。
  • 有限制的通配符:
    在这里插入图片描述
public class Test2 {
    public static void main(String[] args) {
        Dd dd = new Dd();
        List<String> stringList = new ArrayList<>();
        dd.test(stringList);
        List<Integer> integerArrayList = new ArrayList<>();
        dd.test(integerArrayList);
    }
}

class Dd{
    //test方法需要一个list集合的参数,不确定list集合到底存的数据类型是什么
    public void test(List<?> list){

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值