【问题标题】:how to iterate in List<List<Integer>> in java and set their values as we do in a normal int a[i][j] matrix type [duplicate]如何在 Java 中迭代 List<List<Integer>> 并设置它们的值,就像我们在普通 int a[i][j] 矩阵类型中所做的那样 [重复]
【发布时间】:2019-08-25 09:37:25
【问题描述】:

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

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);
}

【问题讨论】:

  • array.get(i).get(j)
  • 但是如何设置其中的值

标签: java matrix arraylist


【解决方案1】:

您可以像使用两个 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);
}

你可以把上面的代码和这个联系起来:

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;
    } 
}

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

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

如果是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();
}

【讨论】:

  • 哪里 scn.nextInt();基本上是您想要填充该特定元素的值。
  • @hjr2000 是的,你是对的。在这种情况下,OP 正在从控制台获取输入,该输入已使用 scn.nextInt(); 检索到;
【解决方案2】:

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

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 

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

【讨论】:

  • 请问这个'Int'类型是什么?
  • @hjr2000 它是 int 的盒装版本,因为 Java 中的通用整数不是“对象”,因此可以与泛型一起使用。装箱和拆箱是自动发生的,因此无需担心显式转换等。
  • 拉斯穆斯谢谢。这有点令人困惑,因为显然 Java 中没有 Int 包装类,并且 Int 类没有在 sn-p 中定义。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-09-13
  • 2013-06-17
  • 2021-07-16
  • 2021-08-24
  • 2020-10-27
  • 2018-05-30
  • 2019-08-31
相关资源
最近更新 更多