-1

If I create a duplicate array like this in java is it correct ?

int [] array = { 10, 20 , 5 , 67 , 4} ;

int  [] d_array =  array ;
MAV
  • 7,260
  • 4
  • 30
  • 47

3 Answers3

3

That's not creating a duplicate array. That's creating a new reference to an existing array. Modifying one will modify "both".

You want to look into the System.arrayCopy() method to create a new copied instance of some array.

Kon
  • 10,702
  • 6
  • 41
  • 58
  • 1
    Additional note: this works good for arrays of primitive and immutable object references because `System.arrayCopy` provides a shallow copy of the array. – Luiggi Mendoza Feb 02 '15 at 20:11
1

See Kon's answer. Try this:

int [] array = new int[]{ 10, 20 , 5 , 67 , 4} ;

        int  [] d_array =  array.clone();

Now there are to different references

Johan
  • 475
  • 4
  • 17
  • I would suggest using `System.arrayCopy()` instead of `clone()`. There are various drawbacks of clone. See Joshua Bloch's Effective Java for a summary of some reasons to prefer avoiding clone. – Kon Feb 02 '15 at 20:10
  • None of those reasons really apply to arrays, but there's also `Arrays.copyOf`, which is simpler to use than `arraycopy`. – Louis Wasserman Feb 02 '15 at 20:12
  • Ok because on this question it should not matter what you use: http://stackoverflow.com/questions/7179251/ – Johan Feb 02 '15 at 20:13
  • Yes, you are both correct. – Kon Feb 02 '15 at 20:14
0

in this case if you change any item in the first array it will be changed in the second, for example if you write:

array[0] = 5;

then also d_array[0] will become 5

to copy an array without having the same reference, replace:

int [] d_array = array ;

with

int [] d_array = array.clone();
Nawar Khoury
  • 170
  • 2
  • 13