Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Integer in ArrayList<ArrayList<Integer>>

Tags:

java

arraylist

please help meto add integer in the ArrayList inside an ArrayList.. Here is the code..

ArrayList<ArrayList<Integer>> player = new ArrayList<ArrayList<Integer>>(10);
ArrayList<Integer> array = new ArrayList<Integer>(10);
array.add(1);
array.add(2);
array.add(3);
array.add(4);
array.add(5);

player.add(array);
player.add(array);

If i check what's inside array and player using debug..

array[1,2,3,4,5]
player[[1,2,3,4,5],[1,2,3,4,5]]

Now, i want to add Integer on player's ArrayList slot 0 using this:

player.get(0).add(6);

but instead of getting of this:

player[[1,2,3,4,5,6],[1,2,3,4,5]]

i got this:

player[[1,2,3,4,5,6],[1,2,3,4,5,6]]

In short, player's ArrayLost slot 0 and slot 1 received the integer that i'ved add..

Please help.. Thanks in advance.. :)

like image 519
Michael De Chavez Avatar asked Jul 16 '26 12:07

Michael De Chavez


1 Answers

You added the same ArrayList to both entries of the player ArrayList. Both entries of the player ArrayList are exactly the same object.

You should make a second ArrayList:

ArrayList<Integer> array2 = new ArrayList<Integer>();

Then add it as the second item of the player ArrayList.

like image 172
Matthew Gunn Avatar answered Jul 18 '26 00:07

Matthew Gunn