I have tried for the last two days to get some code to work, first with maps and then arrayLists. It is a nested for loop that I am trying to populate a data structure with as the loops are iterated. For some reason it is filling my final data structure (an arrayList of arrayLists called DataArrays2.getCinemaRowLayout2()) with the results of the last iteration. By this I mean that ALL arrayLists that were added are ALL duplicates of the FINAL iteration. I have no idea why this is happening!
An example of 2 iterations each with a different input can be seen here: [[o, o, o, o], [o, o, o, o]]. I appreciate that it might not be the best structure to use but I am running out of time so please accept my apologies.
Any help much appreciated!
for (int i=0; i<Screens.rows; i++){//for loop of screen rows
System.out.println("Please enter how many seats and blank spaces in this row");
Screens.columns = Integer.valueOf(scanInValue.next());
for(int j=0; j<Screens.columns; j++){//for loop of seats in row
System.out.println("Please enter 'o' for a seat or press enter for a space");
in = scanInValue.next();
DataArrays2.getCinemaRowLayout().add(j, in);//seats in a row arraylist
}
DataArrays2.getCinemaRowLayout2().add(i, DataArrays2.getCinemaRowLayout());//arraylist of row arraylists
DataArrays2.getCinemaRowLayout().clear();//clears seats arrayList
}
DataArrays2.getScreenMapLayout().put(showingName, DataArrays2.getCinemaRowLayout2());//map of arraylists
BookingSystem2.saveShowing(DataArrays2.getScreenMapLayout()); //saves map to file
Java passing is by object reference, meaning that when you return an Object, you’re returning the location in memory of that Object. So for each run through that loop, you’re modifying the same ArrayList (the property of CinemaRowLayout). If you want to get a separate instance every time, you’ll have to create a new ArrayList from the contents of CinemaRowLayout and add that NEW collection to the map. Right now you’re adding that same object into your map over and over again, and then making changes on that object.
Alternately, you could have DataArrays2.getCinemaLayout() return a new instance every time. If that’s the case, your innerLoop would look something like this: