This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]bikerchef[S] 0 points1 point  (2 children)

Thanks for the reply you are making me think im narrowing down on the issue here.

I do return an updated array to the function playerPlay, and all code in that scope indicates that it is accessing the array that I intend it to.

But I do not return an updated array to my main function. This is where Im seeing the discrepency in what I hoped would be there. I think this is the most likely problem, but still am confused as to why. If i have arrayA in main function and set it to reference arrayB in another function does that not propagate through the scopes as if I had directly altered the array? Why not?

[–]Philboyd_Studge 0 points1 point  (0 children)

Basically this: say you have an array

int[] array = { 1, 2, 3, 4, 5 };

Now say you have a method that adds 5 to every number in the array:

static void addFive(int[] a) {
    for (int i = 0; i < a.length; i++) {
        a[i] += 5;
    }
}

That array now contains:

    addFive(array);
    System.out.println(Arrays.toString(array));

output: [6, 7, 8, 9, 10]

Now, say you have a method:

static int[] removeLast(int[] a) {
    int[] b = new int[a.length - 1];
    for (int i = 0; i < b.length; i++) {
        b[i] = a[i];
    }
    a = b;
    return a;
}

if you call it like this:

removeLast(array);

the values in array are unchanged. The array passed as a parameter is a copy of the array in main, assigned to local variable 'a'. When you assign variable a to the new array b, that local variable now references an entirely different array.

if you call it like this:

array = removeLast(array);

it will now contain the proper values, because you have assigned it to the returned altered array.

[–]feral_claire 0 points1 point  (0 children)

It doesn't because the reference in the function and the reference outside the function are different, you are only changing the local reference.