0

System.arraycopy() is a shallow copy method.

For an array of a primitive type, it will copy the values from one array to another:

int[] a = new int[]{1,2};
int[] b = new int[2];
System.arraycopy(a, 0, b, 0, 2);

b will be {1,2} now. Changes in a will not affect b.

For an array of a non-primitive type, it will copy the references of the object from one array to the other:

MyObject[] a = new MyObject[] { new MyObject(1), new MyObject(2)};
MyObject[] b = new MyObject[2];
System.arraycopy(a, 0, b, 0, 2);

b will contain a reference of new MyObject(1), new MyObject(2) now. But, if there are any changes to new MyObject(1) in a, it will affect b as well.

Are the above statements correct or not?

3
  • 2
    What are your thoughts on this so far? Have you tried writing some sample code? Commented May 23, 2011 at 19:06
  • Why not open up an IDE and find out? Commented May 23, 2011 at 19:07
  • So no sample code -1, not IDE -1? if you are a professor you will be out next semester. Sometimes I need a quick answer. Did you ask your co-worker some questions before you actually tried them before? If never, you are TOOOOOOOO smart. If you are a such smart guy, you need to be patient to other ordinary people. please ignore my any further questions later because most of time i may just ask without any sample and IDE things. Commented May 23, 2011 at 20:42

2 Answers 2

0

Above statements are correct or not?

Yes, you are correct.

System.arraycopy always does a shallow copy, no matter if the array contains references or primitives such as ints or doubless.

Changes in array a will never affect array b (unless a == b of course).

But if any changes of new MyObject(1) in a, it will affect b as well.

Depends on what you mean. To be picky, a change to the new MyObject(1) will neither affect a nor b (since they only contain references to the object, and the reference doesn't change). The change will be visible from both a and b though, no matter which reference you use to change the object.

Sign up to request clarification or add additional context in comments.

Comments

0

You're correct as long as you're specifically modifying properties and calling methods on your objects.

If you change where the reference points, for example with a[0] = new MyObject(1), then even though the objects were created with the same initialization data, they will now point to different instances of the object and a change to one instance will not be seen in the other reference (in array b).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.