This question is a followup for this one..
int tmp;
int[][] Key = new int [TopSubKey.length+BottomSubKey.length][TopSubKey.length];
int[][] KeyChoiceTable = {{14,17,11,24,1,5},{3,28,15,6,21,10},{23,19,12,4,26,8}}
int [][] KeySelection = new int [KeyChoiceTable.length][KeyChoiceTable[0].length];
List<int [][]> list = new ArrayList<int [][]>();
int row,col,x;
for(int l =0;l<3;l++) {
for(int i=0;i<KeyChoiceTable.length;i++){
for(int j=0;j<KeyChoiceTable[0].length;j++){
row = 0;
col = 0;
x = KeyChoiceTable[i][j];
while(x>7){x=x-7; row=row+1;}
col = x-1;
KeySelection[i][j] = Key[row][col];
}
}
list.add(KeySelection);
System.out.print(list.size());
}
If you could just have a look.. because the problem seems so stupid but its killing me.
The Lopp runs 2 times, What I am expecting from the last line is for each loop to store the 2D Array in the list at index 0, and therefore the second loop stores the second 2D Keyselection in the list at index 1.
Whenever i add to the Arraylist (list) the new additiion overwrittes all the other causing all entries to be the same as the last.. I have been trying all day, its the same if i use vectors or stacks.. what is going on ?
When you add
KeySelectiontolist, you’re really adding a reference to it, not a copy. When you changeKeySelectionon the next iteration, the change is also reflected in thelist. To avoid this, declareKeySelectionin the same scope as you add it tolist:Then each entry in
listis a different Array.