常见的泛型标识符:
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] + "]");
}
}
泛型接口
- 实现类时,确定具体类型
- 实现类依旧没有指定具体类型,让接口的泛型跟着实现类的泛型,创建对象时才为具体。
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及其以上的父类