首页 > 解决方案 > 将 ArrayList 存储在 2d 数组 Java 中

问题描述

如何将 ArrayList 存储在二维数组中?

我试过这样,但它不起作用:

ArrayList<Integer> arrList = new ArrayList<Integer>();
ArrayList<Integer>[][] arr = new ArrayList<Integer>[9][9];

但它甚至不允许我声明 ArrayList-Array。

有没有办法将列表存储在二维数组中?

提前致谢!

标签: javaarrayslist

解决方案


您不能在 Java 中创建泛型类型的数组。但这编译:

ArrayList<Integer> arrList = new ArrayList<Integer>();
ArrayList<Integer>[][] arr = (ArrayList<Integer>[][]) new ArrayList[9][9];
arr[0][0] = arrList;

为什么不能创建这些数组?根据泛型常见问题解答,由于这个问题

Pair<Integer,Integer>[] intPairArr = new Pair<Integer,Integer>[10]; // illegal 
Object[] objArr = intPairArr;  
objArr[0] = new Pair<String,String>("",""); // should fail, but would succeed 

推荐阅读