There are 2 types of data in java;
-
Primitives: These are basic data types, primitive variables save simple values. When you assign a value to this variable, it is overwritten
-
Referenced : Referenced variables do not store any value or data, but only store the memory address in which the data is stored.
Here is a visual example of the difference:
Explanation: The variable a
stores the value 77, while the variable persona
has the memory address stored in which the value is in this case the position B10
.
Here you have a table that I found that shows what type of data is each:
SOLUTION
In your case the array is a referenced type, therefore when assigning the array a
to the array b
the only thing you indicate is the position of this, therefore the two indicate the same memory space and equal to which you change the data, the results will be seen in both already point to the same sition.
Explanation:
At first you may not see the logic of it, the usefulness of this comes when passing data, for example; Let's say that you have 2 functions, Función A
: duplicates any string that happens to you and Función B
duplicates all the data within the array.
When you pass the parameters to the Función A
you are passing a primitive data therefore when it finishes processing the String, it has to do a return to be able to see the final result, nevertheless in the Funcion B
you are passing it a revered data ( that is to say, position of memory ), therefore when the function finishes processing the array and duplicates the information inside it. It is not necessary to make any return since the original array has been modified and in any place that accesses this array the change will be notified.
In your case there are several ways to make a single copy of data from your array, without passing the memory address.
-
One of them has already been indicated to you in the answers, create another array and use a loop to make a copy of the values one by one. (Although it's a little bit botched)
-
By default java has its own methods to deal with this:
-
Object.clone (): Taking into account that the array is an object you can use this method to make a complete copy of the array:
int[] a = new int[]{1,2,3,4,5};
int[] b = a.clone();
-
System.arraycopy (): It is the best way to make a partial or complete copy of an array, you can indicate the positions of each array and the number of elements to copy ( System.arraycopy ( original, index_original, destination, index_destination, quantity) )
int[] a = {1,2,3,4,5};
int[] b = [a.length];
System.arraycopy(a, 0, b, 0, a.length);
There are other methods to make the copy although these 2 would be the most effective. You have more references in this post that treat exactly how to make a copy of an array without avoiding the reference