I want to add an array of integers to an ArrayList
. The elements are filled with valid information under some conditions; otherwise the array is fill with -1.
List<int []> starArray = new ArrayList<>();
int [] star = {-1, -1, -1};
for (int i = 0; i < 10; i++) {
if (i < 5) {
star[0] = i;
star[1] = 2*i;
star[2] = 3*i;
starArray.add(star);
} else {
star[0] = star[1] = star[2] = -1;
starArray.add(star);
}
}
Problem is that as soon as it goes to the else
and set star = 0
, all of the elements in starArray
will set to -1. That means, after the loop, I get all -1 in the starArray
. I want this result
0#0#0
1#2#3
2#4#6
...
-1#-1#-1
It seems that a reference is added to starArray
. What I am trying to explain is that I want to create a temp array (star) with 3 elements. So star will take up 96 bytes. Then I move this 96 bytes to an ArrayList. Next I create another 3 element data in the same location of star and push another 96 bytes to ArrayList. So, by pushing two star
to ArrayList, I will use
96 bytes => original star
96 bytes => first element of ArrayList
96 bytes => second element of ArrayList
So, how can I fix that?