Java 泛型

本文最后更新于 2024年9月21日 下午

泛型数组

创建

1
2
3
4
5
6
7
import java.util.*;

public classListOfGenerics<T> {
private List<T> array = new ArrayList<T>();
public void add(T item) { array.add(item)};
public T get(int index) { return array.get(index)};
}

不能创建泛型数组,一般解决方案是在任何想要创建泛型数组的地方使用ArrayList

通配符

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Fruit {
}

class Apple extends Fruit {
}

class Banana extends Fruit {
}

class Jonathan extends Apple {
}

public class CovariantArrays {
public static void main(String[] args) {
Fruit[] fruit = new Apple[10];
fruit[0] = new Apple();
try {
fruit[1] = new Banana();
}catch (Exception e){
System.out.println(e);
}
try {
fruit[2] = new Fruit();
}catch (Exception e){
System.out.println(e);
}
}
}

如果实际数组类型是Apple[],只能在其中放置Apple及其子类,若放入Fruit对象,会在运行时抛出异常

1
2
// incompatible types
List<Fruit> flist = new ArrayList<Apple>();

Apple的List与Fruit的List不同.即使Apple是Fruit的子类,两者在类型上也不等价.

使用通配符解决该问题

1
2
List<? extends Fruit> flist = new ArrayList<Apple>();
// correct

Java 泛型
https://meteor041.git.io/2024/09/12/Java-泛型/
作者
meteor041
发布于
2024年9月12日
许可协议