如何添加阵列ArrayList的? [英] How to add arrays to ArrayList?
本文介绍了如何添加阵列ArrayList的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个int [3] [3]数组,它仅包含0或1的值,
如果值是1我要添加此值的坐标ArrayList中为int [2]数组,但我不知道为什么它总是添加最后1价值坐标,是什么问题?
公共静态无效的主要(字串[] args){ 随机随机=新的随机();
INT [] =坐标INT新[2];
ArrayList的< INT [] GT; ArrayList的=新的ArrayList<>();
INT [] []板=新INT [3] [3]; 的for(int i = 0; I< board.length;我++){
对于(INT J = 0; J<主板[I]。长度; J ++){
板[I] [J] = random.nextInt(2);
}
} 的for(int i = 0; I< board.length;我++){
对于(INT J = 0; J<主板[I]。长度; J ++){
System.out.print(板[I] [J] +);
如果(板[I] [J] == 1){
坐标[0] = I;
坐标[1] = j的;
arrayList.add(坐标); }
}
的System.out.println();
} 的System.out.println(包含值1细胞的坐标); 对于(INT [] coordianate:ArrayList的){
的for(int i = 0; I< coordianate.length;我++){
System.out.print(coordianate [I] +);
}
的System.out.println();
}
}
}
输出:
1 0 1
1 1 0
1 1 0
包含1值单元格的坐标
2 1
2 1
2 1
2 1
2 1
2 1
解决方案
您需要创建新的坐标
阵列每个 I
要在列表的地方,Ĵ
对。现在要放置的同一阵列的多次,它可以记住最后一组对。
在你需要换句话说
如果(板[I] [J] == 1){
坐标= INT新[2]; //添加此行
坐标[0] = I;
坐标[1] = j的;
arrayList.add(坐标);}
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();
}
}
}
output:
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
解决方案
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.
In other words you need to
if (board[i][j] == 1) {
coordinates = new int[2];//add this line
coordinates[0] = i;
coordinates[1] = j;
arrayList.add(coordinates);
}
这篇关于如何添加阵列ArrayList的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文