So I’ve got this code which will add the numbers 1-9 into separate ArrayLists if the ArrayList doesn’t exist. However, even though I print the ArrayLists(and it gets me all the correct numbers), when I print the .size of the ArrayList, it gives me 1 instead of 9. I hope you understand my problem. Here’s the code:
ArrayList[][] tillatnaSiffror = new ArrayList[9][9];
for(int i=0;i<9;i++){
for(int ruta=0;ruta<9;ruta++){
if(tillatnaSiffror[i][ruta] == null){
for(int add=1;add<=9;add++){
tillatnaSiffror[i][ruta] = new ArrayList<Integer>();
tillatnaSiffror[i][ruta].add(add);
System.out.println(tillatnaSiffror[i][ruta]);
}
System.out.println(tillatnaSiffror[i][ruta].size());
}
}
}
That gives me this(although nine times of course): [1][2][3][4][5][6][7][8][9]1
Now I’m wondering, WHY do I get 1 instead of 9 when I print .size?
Because you reset the list in each iteration by doing
i.e., you create a new list, throwing away the previous one for each digit you add!
Try moving out the creation of the list:
Ideone.com demo
As a side note, I would suggest to avoid arrays here, and use Java collections all the way. Consider for instance to use a structure like
List<List<Set<Integer>>>.