I want to set array2
to array1
in Java alike below but it doesn't work.
int[] array1 = new int[3]{1,2,3};
int[] array2 = new int[3];
array2 = array1;
What is wrong with that?
I want to set array2
to array1
in Java alike below but it doesn't work.
int[] array1 = new int[3]{1,2,3};
int[] array2 = new int[3];
array2 = array1;
What is wrong with that?
When you assign the reference of array1
to array2
you create a shallow copy of the array; the two references point to the same array. I assume you wanted a deep copy and you can use Arrays.copyOf(int[], int)
to get one. Also, you don't need new[]
and an explicit size. That could look something like
int[] array1 = { 1, 2, 3 };
int[] array2 = Arrays.copyOf(array1, array1.length);
That second line is POINTLESS. You are creating a new array, filled with 0 in each slot.
Then the following assignment throws away that array! You end up with two variables referencing the exact same array ("location in memory").
If you want two different array objects with the same content, you have to iterate the first array and copy each slot, one by one. Or use System.arrayCopy() for better performance!
The statement int [] array1 = new int [3] {1,2,3};
when compiled gives a syntax error. The corrected statement is without the size of the array:
int [] array1 = new int [] {1,2,3};
Or, you can even do this (is called as array literal syntax):
int [] array1 = {1,2,3};
When you print the contents of the array using the following statement: System.out.println("Array 1: " + Arrays.toString(array1));
you will see result: Array 1: [1, 2, 3]
The rest of the code works fine, as expected.
int[] array1 = new int[] {1,2,3};
System.out.println("Array 1: " + Arrays.toString(array1));
int[] array2 = new int[3];
System.out.println("Array 2: " + Arrays.toString(array2));
array2 = array1;
System.out.println("Array 2: " + Arrays.toString(array2));
I had used the java.util.Arrays utility class to print the elements of the array. Another way to do it is to iterate over the array elements and print each of them using a for-loop.
The output on the console for the above code:
Array 1: [1, 2, 3]
Array 2: [0, 0, 0]
Array 2: [1, 2, 3]
The array2
initially shows [0, 0, 0]
as its values. This is because you created an array without assigning any values; and the default value of elements for an int
array is zero.