泛型 ETKV


常见的泛型标识符:
E:Element
T:Type
K:键值对的键
V:键值对的值

不同的泛型,在何时确定为具体?

泛型类

创建对象时,确定具体类型

public class TimeTest {
    public static void main(String[] args) {
        Student<Integer> student = new Student<>();
    }
}

class Student<E> {
    private E e;
    public E getE() { return e; }
    public void setE(E e) { this.e = e; }
}

泛型方法

位置:传参括号中
1.非静态方法:方法内部的泛型,会根据类的泛型去匹配。
同上public void setE(E e) { this.e = e; }

2.静态方法:静态方法中的泛型,必须声明出自己独立的泛型。在调用方法时,才确认为具体。

public class TimeTest {
    public static void main(String[] args) {
        String[] arr1 = {"张三", "李四", "王五"};
        Integer[] arr2 = {11, 22, 33};
        Double[] arr3 = {11.1, 22.2, 33.3};

        printArray(arr1);
        printArray(arr2);
        printArray(arr3);
    }

    public static <T> void printArray(T[] arr) {
        System.out.print("[");
        for (int i = 0; i < arr.length - 1; i++) {
            System.out.print(arr[i] + ", ");
        }
        System.out.println(arr[arr.length - 1] + "]");
    }
}

泛型接口

  1. 实现类时,确定具体类型
  2. 实现类依旧没有指定具体类型,让接口的泛型跟着实现类的泛型,创建对象时才为具体。
public class TimeTest {
    public static void main(String[] args) {
        InterAImpl a = new InterAImpl();
        InterBImpl<String> b = new InterBImpl<>();
    }
}

interface Inter<E> {
    void show(E e);
}

class InterAImpl implements Inter<String>{
    @Override
    public void show(String s) { }
}

class InterBImpl<E> implements Inter<E>{
    @Override
    public void show(E e) { }
}

泛型通配符

?,任意类型
有异常的风险,不推荐

泛型的限定

? extends Employee:Employee及其以下的子类
? super Employee:Employee及其以上的父类

  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值