如何在 Java 中的 List<List<Integer>> 中迭代并设置它们的值,就像我们在普通的 int a[i][j] 矩阵类型中所做的那样

Nam*_*han 1 java arraylist matrix

我正在尝试使用 arrayList,因为它在许多编码比赛中被要求。我想熟悉数组列表,就像我熟悉普通的 int 数组一样。它需要 2 个不同的 arrayList,然后首先我们将元素添加到一个用于行元素的数组列表中,另一个用于列元素。

List<List<Integer>> arr = new ArrayList<List<Integer>>();
List<Integer> arrCol = new ArrayList<Integer>();
Scanner scn = new Scanner(System.in);
for (int i = 0; i < arr.size(); i++) {
    for(int j = 0; j < arrCol.size(); j++) {
        int x = scn.nextInt();
        arrCol.add(j, x);
    }
    arr.add(i, arrCol);
}
Run Code Online (Sandbox Code Playgroud)

ras*_*s91 7

我认为您要问的是如何做到这一点:

List<List<Int>> arrayList = new ArrayList(); //Java usually infers type parameters in cases as these
for(int i = 0; i < desiredSize; i++){
    List<Int> listAtI = new ArrayList ();
    for(int j = 0; j < rowLength; j++){
        listAtI.set(j, 0);  //sets the element at j to be  0, notice the values are Int not int, this is dues to Javas generics having to work with classes not simple types, the values are (mostly) automatically boxed/unboxed
    }
    arrayList.set(i, listAtI);
}

arrayList.get(5); //returns the list at index 5
arrayList.get(5).get(5) // returns values from column 5 in row 5 
Run Code Online (Sandbox Code Playgroud)

如果您一般不熟悉列表,阅读此处的答案应该会提供有关何时使用哪种类型的列表的有价值的信息


Rak*_*lam 5

您可以使用两个 for 循环来执行类似于我们对二维数组所做的操作:

int rowSize = 5;
int colSize = 3;
List<List<Integer>> arr = new ArrayList<List<Integer>>();
for (int i = 0; i < rowSize; i++) {
    List<Integer> arrRow = new ArrayList<Integer>();
    for (int j = 0; j < colSize; j++) {
        int x = scn.nextInt();
        arrRow.add(x);
    }
    arr.add(arrRow);
}
Run Code Online (Sandbox Code Playgroud)

您可以将上面的代码与此相关联:

int rowSize = 5;
int colSize = 3;
int[][] arr = new int[rowSize][colSize];
for (int i = 0; i < rowSize; i++) {
    for (int j = 0; j < colSize; j++) {
        int x = scn.nextInt();
        arr[i][j] = x;
    } 
}
Run Code Online (Sandbox Code Playgroud)

从该列表中获取数据更简单。对于上面的第二个代码(使用数组),我们可以使用以下方法打印二维数组的所有值:

for (int i = 0; i < rowSize; i++) {
    for (int j = 0; j < colSize; j++) {
        System.out.print(arr[i][j] + " ");
    }
    System.out.println();
}
Run Code Online (Sandbox Code Playgroud)

在arraylist的情况下,可以做类似的事情:

for (int i = 0; i < rowSize; i++) {
    for (int j = 0; j < colSize; j++) {
        System.out.print(arr.get(i).get(j) + " ");
    }
    System.out.println();
}
Run Code Online (Sandbox Code Playgroud)