javaarrayslistmultidimensional-array

How to set value of cell in List<int[][]>?


I have a list List<int[][]> orgnisms = new ArrayList<>();, which I have populated a few empty (only 0 values) tables and I want to set the value of certain cells now. For example, I want the first table from list and cell [1][1] to have a value of 1. How do I accomplish that?

EDIT:

I have a problem because orgnisms.get(0)[1][1] = 1; adds the value 1 to each table in list, not only table which has index 0...

Here is my code to generate a new empty multi-dimensional array which then gets added to the orgnisms list:

private void newEmptyArrays(){
        int[][] emptyTable = new int[n][n]; 
        for( int[] ii : emptyTable) 
            for (int i : ii)
                i = 0;

        for(int i=0;i<mi;i++)  
            orgnisms.add(emptyTable);

}

Solution

  • List<int[][]> orgnisms = new ArrayList<>();
    

    each element within the list is a multi-dimensional array, hence if you want to access any of them you'll first need to retrieve it through the List#get method then perform some operations on it i.e

    orgnisms.get(0)[1][1] = 1;
    

    orgnisms.get(0) will retrieve the reference to the multi-dimensional array, then [1][1] will index into row 1 and column 1 of the retrieved multi-dimensional array and assign a value 1 to it.

    Update

    I have a problem because orgnisms.get(0)[1][1] = 1; adds the value 1 to each table in list, not only table which has index 0...

    Look carefully at your last loop, you're storing multiple references to the same multi-dimensional array within the orgnisms list thus it makes sense for such behavior to happen.

    Also, as per your update, the code is not doing what you think it's. In fact, the nested for loops are not doing anything to the emptyTable multi-dimensional array. However, by default, all the arrays inside emptyTable have a value of 0 set to each element anyway, meaning attempting to set them to 0 again is redundant.

    That said, you can change your method accordingly:

    private void newEmptyArrays(){
          for(int i = 0; i < mi ; i++){  
             int[][] emptyTable = new int[n][n]; 
             orgnisms.add(emptyTable);
          }
    }