java - 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?
解决方案
在 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>>());
}
推荐阅读
- c# - 如何更新由 webhook 触发的 azure 函数中的记录?
- npm - 无法安装 expo-cli ,抛出错误并花费大量时间
- c# - 是否可以以编程方式生成包含组织结构图的 Excel 文件?
- c++ - dtor 中的这个 unique_lock 是否有任何用途?
- javascript - 使用 Materialize-CSS 和 React 的 TypeError
- arrays - 如何改变这个 foreach 就像 for (i=0;i
我是使用 ejs 的新手,我想将我的数据库数据传递给我的 ejs 文件,但我想将 forEach 语法更改为 for(i=0;i
我找到了一个代码来显示它,但它带来了我所有的数据库数据,我只想从我的数据库中传递 4 个数据
这是我的 server.js 代码
var hotelS
- python - 如何根据字典的值(也可以是列表)动态生成 SQLite 插入查询?
- git - git 不会使用 pull 检索远程标签,但可以使用 fetch
- javascript - 是否有任何 npm 包用于计算 doc/docx 文件的字数?
- json - 如何使用顶部有图像的 Json 制作表格