java - How to add arrays to ArrayList? -
i have int[3][3] array , contains 0 or 1 values, if value 1 want add coordinates of value in arraylist int[2] array, don't know why add last 1-value coordinates, what's 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]; (int = 0; < board.length; i++) { (int j = 0; j < board[i].length; j++) { board[i][j] = random.nextint(2); } } (int = 0; < board.length; i++) { (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 contain 1 value"); (int[] coordianate : arraylist) { (int = 0; < coordianate.length; i++) { system.out.print(coordianate[i] + " "); } system.out.println(); } }
}
output:
1 0 1 1 1 0 1 1 0 coordinates of cells contain 1 value 2 1 2 1 2 1 2 1 2 1 2 1
you need create new coordinates
array each i
,j
pair want place in list. placing same array multiple times remembers last set pair.
in other words need
if (board[i][j] == 1) { coordinates = new int[2];//add line coordinates[0] = i; coordinates[1] = j; arraylist.add(coordinates); }
Comments
Post a Comment