我有一个ArrayLists
叫List<Pair> patternList = new ArrayList<>()
包含许多长度为 2 的模式。例如,对于 A={1,2,3,4} 我创建了一些模式,例如 (1,3)(3,2)...等。我想将这些模式放入二维数组(矩阵)[A][A] 中,模式必须进入矩阵中的特定索引,例如模式 (1,3) 必须进入索引 [3][ 3] 或模式 (3,2) 必须进入 [2][2]。
谢谢。
最佳答案
如果您只想将它们放入第二个索引中。 (编辑以允许每个索引有多个):
List<Pair>[][] matrix = new LinkedList<Pair>[5][5]; //Replace 5 here a getter for the maximum value of A
//Here it's 5 because the max of your example is 4.
//Initialize all positions of matrix to empty list.
for (int r = 0; r < matrix.length; r++){
for(int c = 0; c < matrix[r].length; c++){
matrix[r][c] = new LinkedList<Pair>();
}
}
for (Pair p : patternList){
if (matrix[p.second][p.second] == null)
matrix[p.second][p.second] = new LinkedList<Pair>();
matrix[p.second][p.second].add(p);
}
但这并没有真正使用数组的二维方面;您可以使用一维列表数组完成完全相同的事情:
List<Pair>[] arr = new LinkedList<Pair>[5]; //Replace 5 here a getter for the maximum value of A
//Here it's 5 because the max of your example is 4.
//Initialize all positions of array to empty list.
for (int r = 0; r < matrix.length; r++){
arr[r] = new LinkedList<Pair>();
}
for (Pair p : patternList){
if (arr[p.second] == null)
arr[p.second] = new LinkedList<Pair>();
arr[p.second].add(p);
}
关于java - 如何将 arrayList 元素转换为二维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25209788/