Adding to retrieved ArrayLists

Here is the line

waves.get(selectedWave - 1).add(selectedMonster + selectedMosnterLevel);

waves is an

ArrayList<ArrayList<Integer>>

which means it holds other lists of integers. My problem is, that when i retrieve a specific list of Integers by invoking

waves.get(index)

and then adding an Integer value to it

waves.get(index).add(anInt)

it adds "anInt" to every single list, which is present in the "waves" list. Is this really how it works, or might i be screwing up somewhere else in my code.

Upvotes: 0

Views: 62

Answers (1)

AllTooSir
AllTooSir

Reputation: 49382

it adds "anInt" to every single list, which is present in the "waves" list.

The only plausible reason I can think of is that all the List<Integer> references which are added to the List<List<Integer>> points to the same List<Integer> object . The code below will result in this behavior :

List<List<Integer>> waves = new ArrayList<>();
List<Integer> list1 = new ArrayList<>();
List<Integer> list2 = list1;
waves.add(list1);
waves.add(list1);
waves.add(list2);

Upvotes: 1

Related Questions