0

I want to duplicate an array. Typically, I would just do something like this.

int[] a1 = {1, 2, 3};
int[] a2 = a1

Recently however, I saw my professor do it this way:

int[] ar1 = {1, 2, 3};
int[] ar2 = Arrays.copyOf(ar1);

Is there an advantage between doing it one way over the other? What is the main difference?

Omar N
  • 1,720
  • 2
  • 21
  • 33
  • It is fairly easy to test it yourself. I would guess the down vote comes from that. You can use [Arrays.copyof](http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#copyOf(int[],%20int)) as a reference for your example. – Emz Nov 15 '15 at 01:17

2 Answers2

5

In the first case, both arrays point to the same object. So modifying one will modify the other as well.

int[] a1 = {1, 2, 3};
int[] a2 = a1
a1[0] = 15;
System.out.println(a2[0]); //15

In the second case, a true copy is created, so modifying one will not affect the other.

int[] a1 = {1, 2, 3};
int[] a2 = Arrays.copyOf(a1, 3);
a1[0] = 15;
System.out.println(a2[0]); //1

If you want more information about the details of copying in Java, see the second answer to How do I copy an object in Java?

Community
  • 1
  • 1
tixopi
  • 486
  • 3
  • 14
  • @OmarN The second answer to http://stackoverflow.com/questions/869033/how-do-i-copy-an-object-in-java provides a lot more detail about copying in Java if you're interested :) – tixopi Nov 15 '15 at 01:20
2

I completely agree with @tixpoi's post, but I think this is the right place to add, that the first example of yours is called shallow copy and the "true copy" is called deep copy.