如何将数组添加到 ArrayList?

问题描述:

我有一个 int[3][3] 数组,它只包含 0 或 1 个值,如果值为1,我想把这个值在ArrayList中的坐标添加为int[2]数组,但不知道为什么总是添加最后一个1值的坐标,有什么问题?

I have an int[3][3] array and it contains only 0 or 1 values, if the value is 1 I want to add the coordinates of this value in the ArrayList as int[2] array, but I don't know why it always add the last 1-value coordinates, what's the problem?

public static void main(String[] args) {

    Random random = new Random();
    int[] coordinates = new int[2];
    ArrayList<int[]> arrayList = new ArrayList<>();
    int[][] board = new int[3][3];

    for (int i = 0; i < board.length; i++) {
        for (int j = 0; j < board[i].length; j++) {
            board[i][j] = random.nextInt(2);
        }
    }

    for (int i = 0; i < board.length; i++) {
        for (int j = 0; j < board[i].length; j++) {
            System.out.print(board[i][j] + " ");
            if (board[i][j] == 1){
                coordinates[0] = i;
                coordinates[1] = j;
                arrayList.add(coordinates);

            }
        }
        System.out.println();
    }

    System.out.println("coordinates of cells that contain 1 value");

    for (int[] coordianate : arrayList) {
        for (int i = 0; i < coordianate.length; i++) {
            System.out.print(coordianate[i] + " ");
        }
        System.out.println();
    }
}

}

输出:

1 0 1 
1 1 0 
1 1 0 
coordinates of cells that contain 1 value
2 1 
2 1 
2 1 
2 1 
2 1 
2 1 

您需要为每个 i,j 创建新的 coordinates 数组您想放在列表中的配对.现在你要多次放置同一个数组,记住最后一组.

You need to create new coordinates array for each i,j pair you want to place in your list. For now you are placing same array multiple times which remembers last set pair.

换句话说,你需要

if (board[i][j] == 1) {
    coordinates = new int[2];//add this line
    coordinates[0] = i;
    coordinates[1] = j;
    arrayList.add(coordinates);

}