简体   繁体   中英

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM