What is wrong with this implimentation of the .add() method?
Here is a simplified version of the primary bug in a much larger hunk of code. If you run this code you will notice that ONLY the 20th iteration of the array1 data gets added to the ArrayList. WHY?! I need all the unique arrays added. Please help.
import java.util.ArrayList;
import java.util.Random;
publicclass listBuilder{
publicstaticvoid main(String args[]){
ArrayList<long[]> uArrayList =new ArrayList<long[]>();
int N = 7, L = 20;
long[] array1 =newlong[N];
long[] array2 =newlong[N];
Random why =new Random();
for (int i=0; i < L; i++){
for (int j = 0; j < N; j++){
array1[j] = (long)why.nextInt(10);
}
uArrayList.add(array1);
}
for (int i = 0; i < L; i++){
System.out.print(i +": ");
array2 = (long[])uArrayList.get(i);
for (int j = 0; j < N; j++){
System.out.print(array2[j] +" ");
}
System.out.println();
}
}
}
[2308 byte] By [
Fontaignea] at [2007-11-26 23:39:23]

# 3
You allocated array1 once.
You set array1[0..n] to some value,
then add array1 to your collection.
You then change array1[0..n] to some other value,
then add array1 AGAIN to your collection.
So your collection always contains just 1 array,
and the array will only contain the most recent values
(since each iteration of the loop you were erasing old values)
# 4
Try this:
public class listBuilder {
public static void main(String args[]){
ArrayList<long[]> uArrayList = new ArrayList<long[]>();
int N = 7, L = 20;
Random why = new Random();
for (int i=0; i < L; i++){
long[] array1 = new long[N];
for (int j = 0; j < N; j++){
array1[j] = (long)why.nextInt(10);
}
uArrayList.add(array1);
}
for (int i = 0; i < L; i++){
System.out.print(i + ": ");
long[] array2 = (long[])uArrayList.get(i);
for (int j = 0; j < N; j++){
System.out.print(array2[j] + " ");
}
System.out.println();
}
}
}
# 6
> So your collection always contains just 1 array,
> and the array will only contain the most recent
> values
> (since each iteration of the loop you were erasing
> old values)
Well, not exactly. the collection will contain 20 times the same array object, as it is a list not a set.
# 7
> > So your collection always contains just 1 array,
> > and the array will only contain the most recent
> > values
> > (since each iteration of the loop you were erasing
> > old values)
>
> Well, not exactly. the collection will contain 20
> times the same array object, as it is a list not a
> set.
Right. Quite right. I meant the number of distinct Array in his collection is 1.