首页 > 解决方案 > Create a multidimensional generic array of Optionals

问题描述

I want to create a two-dimensional array (yes I know that this is actually an array of arrays) holding Optionals. The normal approach for generic array creation does not work though as it fails with a ClassCastException. Here is my code:

@SuppressWarnings("unchecked")
Optional<Integer>[][] arr = (Optional<Integer>[][]) new Object[5][5];

Is there a way to create such an array, if yes what would be the approach for that?

标签: javagenericsmultidimensional-arrayoptional

解决方案


在 Java 中“创建泛型类型、参数化类型或类型参数的数组是非法的”。“为什么创建泛型数组是非法的?因为它不是类型安全的。如果它是合法的,编译器在其他正确的程序中生成的强制转换可能会在运行时失败并出现 ClassCastException。这将违反由泛型类型系统。[Joshua Bloch - Effective Java]

那么有哪些解决方案能够创建多维数组呢?

推荐的方法是使用容器:

List<List<Optional<Integer>>> arr = new ArrayList<>();
for (int i = 0; i < 5; i++) {
    arr.add(new ArrayList<Optional<Integer>>());
}

推荐阅读