Reputation: 3
I want to make an arraylist
with int[]
as objects
ArrayList<Integer[]> b= new ArrayList<Integer[]>();
Integer[] a= new Integer[2];
for(Integer i=0;i<20;i++){
a[0]=i;
a[1]=i;
b.add(a);
}
for(int i=0;i<20;i++){
System.out.println("line"+i+"= "+b.get(i)[0]+" "+b.get(i)[1]);
}
and the result I get is this
instead of the values( 0 0 1 1 etc), is seems that has saved only the last. I have also tried with type int instead of Integer but the same result
Upvotes: 0
Views: 82
Reputation: 2626
You have to declare a new array for each element you're going to add. Otherwise they all reference the same memory. Declare the array inside the for loop instead of before the loop.
Upvotes: 2
Reputation: 11910
Consider initializing a
within the loop as otherwise you are just writing over the same array the whole time.
Instead of
ArrayList<Integer[]> b= new ArrayList<Integer[]>();
Integer[] a= new Integer[2];
for(Integer i=0;i<20;i++){
a[0]=i;
a[1]=i;
b.add(a);
}
for(int i=0;i<20;i++){
System.out.println("line"+i+"= "+b.get(i)[0]+" "+b.get(i)[1]);
}
consider this:
ArrayList<Integer[]> b= new ArrayList<Integer[]>();
for(Integer i=0;i<20;i++){
Integer[] a= new Integer[2];
a[0]=i;
a[1]=i;
b.add(a);
}
for(int i=0;i<20;i++){
System.out.println("line"+i+"= "+b.get(i)[0]+" "+b.get(i)[1]);
}
As the point is for each loop iteration to make a new array and store new values rather than overwrite the existing ones as if you step through your code you may notice you how don't ever allocate a new array within the loop.
Upvotes: 2