How to add arrays to ArrayList?

前端 未结 3 1941
天涯浪人
天涯浪人 2021-01-24 16:11

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 w

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-24 16:27

    You need to create a new coordinate object every time you add it:

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

    or shorter:

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

    Otherwise you will add the same object multiple times and modify it each time so only the last coordinate remains.

    If you make it a habit to use narrow scoped (temporary) variables, this typically comes naturally as you do not drag state around outside of loops.

提交回复
热议问题