从ArrayList <arraylist <integer>&gt;输出整数在Java </arraylist <integer>

时间:2015-02-14 19:08:07

标签: java arraylist

我制作了一个ArrayList&lt;的ArrayList&LT;整数&gt;&gt;保持棋盘的坐标。我输入数字时遇到了麻烦。当我输出ArrayLists的大小时,它告诉我safeSquares在第一组for循环之后有64个对象,但是在&#34; for(ArrayList innerList:safeSquares)&#34;之后,innerList总是大小为零。线。似乎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 + " ");
  }
}

2 个答案:

答案 0 :(得分:1)

尝试一次一行地浏览代码,并在每行代码后写下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]

答案 1 :(得分:0)

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)坐标索引它。