请注意:在将数组转换为列表时,原始数组和对象数组之间存在差异。即)int[] 和 Integer[]
例如)
int [][] twoDArray = {
{1, 2, 3, 4, 40},
{5, 6, 7, 8, 50},
{9, 10, 11, 12, 60},
{13, 14, 15, 16, 70},
{17, 18, 19, 20, 80},
{21, 22, 23, 24, 90},
{25, 26, 27, 28, 100},
{29, 30, 31, 32, 110},
{33, 34, 35, 36, 120}};
List list = new ArrayList();
for (int[] array : twoDArray) {
//This will add int[] object into the list, and not the int values.
list.add(Arrays.asList(array));
}
和
Integer[][] twoDArray = {
{1, 2, 3, 4, 40},
{5, 6, 7, 8, 50},
{9, 10, 11, 12, 60},
{13, 14, 15, 16, 70},
{17, 18, 19, 20, 80},
{21, 22, 23, 24, 90},
{25, 26, 27, 28, 100},
{29, 30, 31, 32, 110},
{33, 34, 35, 36, 120}};
List list = new ArrayList();
for (Integer[] array : twoDArray) {
//This will add int values into the new list
// and that list will added to the main list
list.add(Arrays.asList(array));
}
致力于 Keppil 的回答;您必须使用 How to convert int[] to Integer[] in Java?
将原始数组转换为对象数组
否则,在正常的 for 循环中将 int 值一一添加。
int iLength = twoDArray.length;
List<List<Integer>> listOfLists = new ArrayList<>(iLength);
for (int i = 0; i < iLength; ++i) {
int jLength = twoDArray[0].length;
listOfLists.add(new ArrayList(jLength));
for (int j = 0; j < jLength; ++j) {
listOfLists.get(i).add(twoDArray[i][j]);
}
}
还要注意 Arrays.asList(array) 会给出fixed-size list; so size cannot be modified。