-2

I have the following:

ArrayList<int[]> lista = new ArrayList<int[]>();

int[] posible_mov = new int[2];

posible_mov[0] = 0;
posible_mov[1] = 0;
lista.add(posible_mov);

posible_mov[0] = 1;
posible_mov[1] = 1;
lista.add(posible_mov);

Well, if I walk the show with arraylist and get all elements method, shows me in both cases:

lista.get(0) => 1, 1 lista.get(1) => 1, 1

WHY?

2 Answers2

2

You adding a reference to the posible_mov into the lista. That's why you always print 1,1 because in the last part of the code you are assigning posible_movthe value 1. You can try to change the order of the assignments and you will see you will print 0,0 instead.

If you want to add several objects, and not reference them, then you can do:

int[] posible_mov = new int[2];

posible_mov[0] = 0;
posible_mov[1] = 0;
lista.add(posible_mov);

posible_mov = new int[2]
posible_mov[0] = 1;
posible_mov[1] = 1;
lista.add(posible_mov);

For further reading check Java Pass by reference or value

Community
  • 1
  • 1
Bruno Caceiro
  • 7,035
  • 1
  • 26
  • 45
0

Your reference variable just override the previous stored values.

So in order to not let that happen, you can create another objects without referencing them or create an another array with a different name if you want to retain both the arrays simultaneously. After the first lista.add() function, you can add one of the below:

posible_mov = new int[2];

or

int[] posible_mov_1 = new int[2]; //Use this variable name for further operations on this object
burglarhobbit
  • 1,860
  • 2
  • 17
  • 32