Benjamin Lowry Benjamin Lowry - 2 months ago 8
Java Question

Array Unexpected Behavior

So I am trying to do a very simple task of taking two identical arrays and setting the first value of the first array to the last value of the second array.

The code below shows me trying to do so with the

numberArray
and
duplicateArray
. The bulk of the code however is me trying to figure out why I am getting a weird result.

System.out.print("Normal array 1: ");
for (int l = 0 ; l < numberArray.length ; l++){
System.out.print(numberArray[l]);
}

System.out.print("Duplicate array 1: ");
for (int l = 0 ; l < duplicateArray.length ; l++){
System.out.print(duplicateArray[l]);
}
System.out.println();

numberArray[0] = duplicateArray[duplicateArray.length - 1];

System.out.print("Duplicate array 2: ");
for (int l = 0 ; l < duplicateArray.length ; l++){
System.out.print(duplicateArray[l]);
}
System.out.println();

System.out.print("Normal array 2: ");
for (int l = 0 ; l < numberArray.length ; l++){
System.out.print(numberArray[l]);
}


This outputs:

Normal array 1: 123
Duplicate array 1: 123
Duplicate array 2: 323
Normal array 2: 323


What makes no sense to me is that even though I am supposedly setting the value one object to another, both are changing.

My understanding of Java is this:

array[x] = array2[y];
//value at index x of "array" now equals value at index y of "array 2"
//however, array2 should not be changed at all since it is just referenced in the above line of code, not mutated


Am I missing something really simple? I've been racking my brains trying to figure this out. Any help would be greatly appreciated.

EDIT:

I have been asked to provide the declaration of my two arrays so here they are:

int[] numberArray = {1, 2, 3};
int[] duplicateArray = numberArray;


This shouldn't make a difference right? Setting one array to another shouldn't link them (or so I think).

Answer

As i commented , your both array pointing to same array in memory

int[] numberArray = {1, 2, 3};
int[] duplicateArray = numberArray; // duplicateArray is just a another name for numberArray

so if you change any value with either of names duplicateArray or numberArray mean you are changing the array in memory which is pointed by both.

So you need to create a new array by adding elements of numberArray to duplicateArray using System.arraycopy;

like this

int[] numberArray = {1, 2, 3};
int[] duplicateArray = new int[numberArray.length];
System.arraycopy( numberArray , 0, duplicateArray , 0, numberArray .length );

View the image for visual view

enter image description here

Comments