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).