gpt4 book ai didi

java - 如何从ArrayList的ArrayList中获取二维数组?

转载 作者:行者123 更新时间:2023-12-01 16:47:21 26 4
gpt4 key购买 nike

我有:

ArrayList<ArrayList<Integer>> adjList = new ArrayList<ArrayList<Integer>>();

我想将其转换为`

int[][] adjL = new int[?][?];

这可能吗?我应该用什么替换数组大小中的 ?

最佳答案

不简单,但这应该对您有帮助:

ArrayList<ArrayList<Integer>> adjList = new ArrayList<>();

Integer[][] result = new Integer[adjList.size()][];//create your array of arrays
for (int i = 0; i < adjList.size(); i++) {
//foreach array you have to inisialize it with the correct size
result[i] = new Integer[adjList.get(i).size()];

//the fill the array with the value of your list
for(int j = 0; j < adjList.get(i).size(); j++){
result[i][j] = adjList.get(i).get(j);
}
}

对于这样的输入:

adjList.add(new ArrayList<>(Arrays.asList(1, 2, 3, 4)));
adjList.add(new ArrayList<>(Arrays.asList(1, 2, 3)));
...
System.out.println(Arrays.deepToString(result));

输出:

[[1, 2, 3, 4], [1, 2, 3]]

关于java - 如何从ArrayList的ArrayList中获取二维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47847756/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com