1

First of all I've been reading to avoid possible duplicates and I have to say this doesn't seem any static declaration issue.

I have this code:

String[] bonoActual = (String[]) it.next();
String[] auxBono = new String[3];
ArrayList<String[]> bonosTemp = new ArrayList<String[]>();
ArrayList<Integer> abosTemp = new ArrayList<Integer>();


System.out.println("Añadiendo: "+bonoActual[0] + "a bonostemp");
bonosTemp.add(bonoActual);

abosTemp.add(abo);
auxBono[0] = aux;
auxBono[1] = String.valueOf(udsPrecio[1]);
auxBono[2] = fecValor;
bonosTemp.add(auxBono);
abosTemp.add(abo);
System.out.println("Añadido: "+auxBono[0] + "a bonostemp");

The values of aux, abo and fecValor are correctly being assigned from other sources, bonoActual is being initialized in a loop and retrieving from other sources and this is the console output:

Añadiendo: BONO DATOS 1 GIGA AGOSTO (-) BONO VOZ 100 MINUTOS AGOSTO (-)a bonostemp
Añadido: BONO DATOS 1 GIGA SEPTIEMBRE (-)a bonostemp

Which is correct, however when I look at bonosTemp while debugging, both entries have this value in the position 0 of the array values:

 BONO DATOS 1 GIGA SEPTIEMBRE (-)

Any ideas why this may be happening?

Lowb
  • 162
  • 1
  • 13
  • Please show a short but *complete* program demonstrating the problem. I strongly suspect the problem is that you're adding multiple references to the same string array, but we can't tell from the code you've given, as you haven't provided the loop. I'm pretty sure this will be a duplicate of lots of others... I'll start looking for one. – Jon Skeet Oct 15 '14 at 16:17
  • See the second part of the answer to http://stackoverflow.com/questions/19843506 – Jon Skeet Oct 15 '14 at 16:18

1 Answers1

2

You are repeatedly adding the same array to bonosTemp. As a result, every element of bonosTemp refers to the same array. When you modify the array, all elements bonosTemp appear to change at once (because they are the same object).

To fix this, add a copy of the array instead:

bonosTemp.add(auxBono.clone());
NPE
  • 486,780
  • 108
  • 951
  • 1,012