Reputation: 23
I am trying a simple code and I can't figure out what is wrong. I am trying to add int[] array to an ArrayList. It gets added correctly. But once I have more than 1 element in the ArrayList, each of the element in the list is replaced by the latest value. I tried looking for possible errors, but I couldn't find any. I am giving my code and output here so that I can get help in figuring out the error in the code.
Code:
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
public class main {
public static void main(String[] args) {
ArrayList<int[]> outer = new ArrayList<int[]>();
int[] list = new int[7];
int total = 2;
int l = 3;
SecureRandom rand = new SecureRandom();
for (int i = 0; i < total; i++)
{
if((i+1) % l == 0)
{
list = new int[7];
outer = new ArrayList<int[]>();
}
else {
for(int j = 0; j < 7; j++)
{
int num = rand.nextInt(100);
list[j] = num;
}
System.out.println(Arrays.toString(list));
outer.add(list);
System.out.println(outer.size());
System.out.println(i);
System.out.println(Arrays.toString(outer.get(i)));
}
}
System.out.println(Arrays.toString(outer.get(0)));
System.out.println(Arrays.toString(outer.get(1)));
}
}
The output I get is:
Output:
[13, 50, 3, 47, 53, 57, 61]
1
0
[13, 50, 3, 47, 53, 57, 61]
[66, 96, 45, 2, 95, 1, 69]
2
1
[66, 96, 45, 2, 95, 1, 69]
[66, 96, 45, 2, 95, 1, 69]
[66, 96, 45, 2, 95, 1, 69]
Upvotes: 0
Views: 2673
Reputation: 1
You changed the values of the same int[]
instance, whatever i
is, and you put the same references of int[]
to outer
, so outer.get(0)
and outer.get(0)
will always be the same.
Upvotes: 0
Reputation: 697
Every time you add a new int[] to the ArrayList, you need to make a new array every time. Just move int[] list = new int[7];
to inside the for loop so that it'll make a new int[] every time.
Upvotes: 0
Reputation: 54204
You are adding the same int[]
instance to the list repeatedly.
else { for(int j = 0; j < 7; j++) { int num = rand.nextInt(100); list[j] = num; } System.out.println(Arrays.toString(list)); outer.add(list); System.out.println(outer.size()); System.out.println(i); System.out.println(Arrays.toString(outer.get(i))); }
Nothing in this list ever calls list = new int[7]
. That means that each time through, you overwrite the contents of list
with new random numbers, then add the same list to the ArrayList
again.
ArrayList
will happily let you add the same object over and over. It's just important to understand that putting an object into the ArrayList
doesn't somehow copy it or anything.
Upvotes: 4