如何将数组添加到ArrayList?

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

public static void main(String[] args) { Random random = new Random(); int[] coordinates = new int[2]; ArrayList 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 

您需要为要放入列表中的每个ij对创建新的coordinates数组。 现在你多次放置相同的数组 ,记住最后一组。

换句话说,你需要

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

每次添加时都需要创建一个新的坐标对象:

 if (board[i][j] == 1) { int[] coordinate = new int[2]; coordinate[0] = i; coordinate[1] = j; arrayList.add(coordinate); } 

或更短:

 if (board[i][j] == 1) { arrayList.add(new int[]{i, j} ); } 

否则,您将多次添加相同的对象并每次修改它,因此只剩下最后一个坐标。

如果你习惯使用窄范围(临时)变量,这通常很自然,因为你不会在循环外部拖动状态。

如果要将Points放入ArrayList,我建议您创建一个带坐标的Point对象。 请参阅下面的代码。 很抱歉这个冗长的回复。

 import java.util.ArrayList; import java.util.Arrays; public class SomeClass { static class Point { int[] coordinates; public Point(int x, int y) { this.coordinates = new int[2]; this.coordinates[0] = x; this.coordinates[1] = y; } public Point() { this(0,0); } public Point(int[] coordinates) { this.coordinates = coordinates; } } public static void main(String[] args) { SomeClass myClass = new SomeClass(); Point a = new Point(); Point b = new Point(5,5); Point c = new Point(new int[]{3,4}); ArrayList arr = new ArrayList(); // adding arr.add(a); arr.add(b); arr.add(c); // retrieve one object int index = 0; Point retrieved = arr.get(index); System.out.println("Retrieved coordinate: " + Arrays.toString(retrieved.coordinates)); retrieved.coordinates[0] = 15; retrieved.coordinates[1] = 51; System.out.println("After change, retrieved coordinate: " + Arrays.toString(retrieved.coordinates)); System.out.println("After change, accessing arraylist index: " + Arrays.toString(arr.get(index).coordinates)); // we received a pointer to the array // changed values are automatically reflected in the ArrayList } } 

这些是你将获得的价值……

 Retrieved coordinate: [0, 0] After change, retrieved coordinate: [15, 51] After change, accessing arraylist index: [15, 51]