-1
public static int[] tranzitie(int[] stare, int x, int y) {
    stare[x] = y;
    return stare;
}

int[] SC = {3,1,1,1};
int[] SN = {3,1,1,1};                             

SN = tranzitie(SC, x, y);

//when i do this, i want to change only SN //but in my case SN = SC

yonuthim
  • 1
  • 1

2 Answers2

1

If you don't want to change the original array, then you must make a defensive copy and work on that copy instead, for example:

public static int[] tranzitie(int[] stare, int x, int y) {
    int[] copy = stare.clone();
    copy[x] = y;
    return copy;
}

See this related discussion which explains in detail how method parameters are passed in Java.

Community
  • 1
  • 1
janos
  • 120,954
  • 29
  • 226
  • 236
0

In Java, arrays are objects, and when you assign an int[] variable or pass one as a parameter, you're actually assigning or passing a reference to the array object.

Thus, in this call:

SN = tranzitie(SC, x, y);

tranzitie gets a reference to the SC array, not a copy of it. The stare parameter will be referring to the same array. Thus, when the method says

stare[x] = y;

it actually modifies SC---not a copy of SC, but the actual array itself.

When the method says return stare, since stare is a reference to the SC array object, the method will return that reference. Then you assign SN to that. The result will be that SN and SC are now references to the same array. The array that you created earlier:

int[] SN = {3,1,1,1}; 

will no longer be accessible (unless you stored the reference somewhere else).

If this is not what you want, then you have to handle your arrays carefully; the CopyOf and CopyOfRange methods in Arrays are helpful in making copies of arrays or parts of arrays.

ajb
  • 31,309
  • 3
  • 58
  • 84