-3

I'm trying to add Arrays of integer to an ArrayList but it seems that each time that a new Array is beeing added, the content of all the others is modified to be the same as the last.

for (int a = 0; a<taille; a++) {
    temp[0] = this.caseX-a; 
    temp[1] = this.caseY;
    this.occupe.add(temp);
    for ( int j = 0; j < this.occupe.size(); j++ )
            System.out.println("element " + j + ": " + this.occupe.get(j)[0] );

The caseX and caseY are two integers and my array is this.occupe.

The output is :

element 0: 4
element 0: 3
element 1: 3
element 0: 2
element 1: 2
element 2: 2
element 0: 1
element 1: 1
element 2: 1
element 3: 1

While it should be :

element 0: 4
element 0: 4
element 1: 3
element 0: 4
element 1: 3
element 2: 2
element 0: 4
element 1: 3
element 2: 2
element 3: 1
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
Chams
  • 20
  • 3
  • 1
    show where the array and ArrayList are declared. – Ousmane D. Jan 06 '18 at 18:09
  • 3
    You always work on the same instance of `temp`, so you are actually overwriting its values on each iteration. You should do `temp = new int[2]` at the beginning of the first `for` loop. – BackSlash Jan 06 '18 at 18:10

1 Answers1

2

You use the same object in each adding.
While you need to add distinct objects in the occupe List.

So instantiate temp in each iteration (in the loop and not before).
But in fact you can do simpler. You don't need to introduce an intermediary variable.

You could simply write :

this.occupe.add(new int[]{this.caseX-a, this.caseY});

The type of element of the temp array is not specified.
So change int[] if required.

davidxxx
  • 125,838
  • 23
  • 214
  • 215