How to change the size of some ArrayList in a 2d ArrayList?

3455 views java
1

I have this class to implement a 2d arraylist. I want the method criaDimensao to put values inside the ArrayList at index position of matriz only but it keeps putting value in all indexes of matriz.

public class Matriz {
private ArrayList<ArrayList<Integer>> matriz = new ArrayList<>();

//constructor
public Matriz(){

}

//constructor
public Matriz(int lenght){
    int c = 0;
    ArrayList<Integer> init = new ArrayList<>();
    while (c < lenght){
        matriz.add(init);
        c +=1 ;
    }
}

public boolean criaDimensao(int index, int tamanhoDimensao){
    for(int i = 0; i < tamanhoDimensao; i++){
        matriz.get(index).add(0); //defalt value 0
    }
    return true;
}

The idea is to have different sizes of ArrayList inside the 'matriz';

answered question

1 Answer

12

Because in the constructor:

ArrayList<Integer> init = new ArrayList<>();
while (c < lenght){
    matriz.add(init);
    c +=1 ;
}

You keep on adding a reference to the same ArrayList in all indices of matriz. So when you call:

matriz.get(index).add(0);

You will be adding it to init, which will be reflected across the entire mariz

Instead you could have something like this in the constructor:

while (c < lenght){
   matriz.add(new ArrayList<Integer>());
   c +=1 ;
}

posted this

Have an answer?

JD

Please login first before posting an answer.