0

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?

prasad_
  • 12,755
  • 2
  • 24
  • 36

3 Answers3

1

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);
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • This is an awesome explanation but I still don't understand your definition of a shallow copy. When I do a shallow copy of array1 into 2, does array2[1] return 2? – Taslim Oseni Jan 14 '19 at 01:13
  • 1
    @Taslim OP is copying the reference, so yes. But if OP did `array2[1] = 3;` **then** `array1[1]` would also equal `3`. Because `array1 == array2` OP's way. – Elliott Frisch Jan 14 '19 at 01:15
0

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!

GhostCat
  • 137,827
  • 25
  • 176
  • 248
0

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.

prasad_
  • 12,755
  • 2
  • 24
  • 36