从 ArrayList<ArrayList<Integer>> in Java 中输出整数

Outputting integers from an ArrayList<ArrayList<Integer>> in Java

我制作了一个 ArrayList< ArrayList< Integer >> 来保存棋盘的坐标。我无法简单地输出数字。当我输出 ArrayLists 的大小时,它告诉我 safeSquares 在第一组 for 循环之后有 64 个对象,但是 innerList 在 "for(ArrayList innerList : safeSquares)" 行之后的大小始终为零。似乎 safeSquares 从未将 arrayLists 传递给 innerList,而是尝试了 64 次。

static ArrayList<ArrayList<Integer>> safeSquares = new ArrayList<ArrayList<Integer>>();
static ArrayList<Integer> squares = new ArrayList<Integer>();

for(int i = 0; i < 8; i++){
  squares.add(i);
  for(int x = 0; x < 8; x++){
    squares.add(x);
    safeSquares.add(squares);
    squares.remove(1);
  }
  squares.clear();
}

for(ArrayList<Integer> innerList : safeSquares) {
  for (Integer number : innerList) {
    System.out.println(number + " ");
  }
}
static ArrayList<ArrayList<Integer>> safeSquares = new ArrayList<ArrayList<Integer>>();
static ArrayList<Integer> squares; 

for(int i = 0; i < 8; i++){
    squares = new ArrayList<Integer>();
    for(int x = 0; x < 8; x++){
       squares.add(x);
 }
 safeSquares.add(squares);
}

for(ArrayList<Integer> innerList : safeSquares) {
    for (Integer number : innerList) {
    System.out.println(number + " ");
    }
}

这行得通。我相信。如果您在看到此内容后无法理解自己的错误,请务必询问。不过,我建议您使用二维数组。如:Array[][] int 并用(x,y)坐标对其进行索引。

尝试一次一行地浏览您的代码,并在每行代码之后写下 square 和 safeSquares 的状态。我想你会发现你并没有达到你的期望!

然后试试这个代码,我不确定它是否正是你想要的,但我认为它更接近...

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

for (int i = 0; i < 8; i++) {
    ArrayList<ArrayList<Integer>> squares = new ArrayList<ArrayList<Integer>>();
    for (int x = 0; x < 8; x++) {
        ArrayList<Integer> pair = new ArrayList<Integer>();
        pair.add(x);
        pair.add(i);
        squares.add(pair);
        }
    safeSquares.add(squares);
}

for (ArrayList<ArrayList<Integer>> outlist : safeSquares) {
    for (ArrayList<Integer> inlist : outlist) {
        System.out.print(inlist);
    }
    System.out.println();
}

这是输出:

[0, 0][1, 0][2, 0][3, 0][4, 0][5, 0][6, 0][7, 0]
[0, 1][1, 1][2, 1][3, 1][4, 1][5, 1][6, 1][7, 1]
[0, 2][1, 2][2, 2][3, 2][4, 2][5, 2][6, 2][7, 2]
[0, 3][1, 3][2, 3][3, 3][4, 3][5, 3][6, 3][7, 3]
[0, 4][1, 4][2, 4][3, 4][4, 4][5, 4][6, 4][7, 4]
[0, 5][1, 5][2, 5][3, 5][4, 5][5, 5][6, 5][7, 5]
[0, 6][1, 6][2, 6][3, 6][4, 6][5, 6][6, 6][7, 6]
[0, 7][1, 7][2, 7][3, 7][4, 7][5, 7][6, 7][7, 7]