I have an IntArray A.
int[] A={1,2,3};
and I copy it to B.
int[] B=A;
now I want to change element in A;
A[1]=B[2];
I would expect A now becomes {1,3,3} where B stays the same {1,2,3}.
Why is B changed to [1,3,3]?
I have an IntArray A.
int[] A={1,2,3};
and I copy it to B.
int[] B=A;
now I want to change element in A;
A[1]=B[2];
I would expect A now becomes {1,3,3} where B stays the same {1,2,3}.
Why is B changed to [1,3,3]?
They both are not individual arrays.
You wrote
int[] B=A;
Because there are pointing to the same array.
If you change A automatically B
changes.
If you want to make B
constant create a new array in the name of B
.
int[] B = new int[3];
As you confused with pass by reference and value :Is Java "pass-by-reference" or "pass-by-value"?
Because you are not copying the array, you are simple working with references.
This mean that if you create an array you are assigning a piece of memory to that variable.
int[] array ----------------> PieceOfMemory
If you "copy" the array as you did you are simply telling another variable to point to the same piece of memory
int[] array ----------------> PieceOfMemory <----------------- int[] secondArray
In this case if you change "PieceOfMemory" is clear that you are changing both of the variables.
If you want to copy the array you have to do like so:
int[] firstArray = {1,2,3};
int[] secondArray = new int[3];
secondArray = (int[]) clone(firstArray);
now what happens is this:
int[] firstArray ---------------------> firstPieceOfMemory
int[] secondArray --------------------> secondPieceOfMemory
But the values are copied.
When you do
int[] B=A;
B
and A
both point to same backing array. B
and A
here are just references pointing to same underlying array.
A ----->[1,2,3]
^
B----------|
To make a new copy you can use Arrays#copyOf or manually create a new array and copy fields one by one.
You need to understand the difference between objects and references.
I.e. B=A;
does not make a copy of the data, but a copy of the reference to the data.
Because B isn't a new array, it's just another name for the array that A refers to.
Yes B also changed to {1,3,3} because A and B are just references actual memory where the array is stored are same for both the array so both array contains same value.