java - 如何将 arrayList 元素转换为二维数组?

标签 java arrays arraylist

我有一个ArrayListsList<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/

相关文章:

java - JButton Windows 外观

java - 唯一注释@GenerateValue

java - 如何创建 TestNg 类

arrays - 如何从 n 个数组中找到公共(public)元素

java重复文本不同时间

c++ - 实现线程安全数组

javascript - 如何使用箭头函数返回数组中的第一项?

使用数组和 while 循环对询问的数字进行 Java 索引

java - List 的 removeIf() 未按预期工作

java - 如何使用 OOP 打印 arrayList 中的最小值?