What exactly does the clone() method in Java return when used on an array?
Does it return a new array with data copied from the original?
Ex:
int[] a = {1,2,3};
int[] b = a.clone();
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
When the
clonemethod is invoked upon an array, it returns a reference to a new array which contains (or references) the same elements as the source array.So in your example,
int[] ais a separate object instance created on the heap andint[] bis a separate object instance created on the heap. (Remember all arrays are objects).If were to modify
int[] bthe changes would not be reflected onint[] asince the two are separate object instances.This becomes slightly more complicated when the source array contains objects. The
clonemethod will return a reference to a new array, which references the same objects as the source array.So if we have the class
Dog…and I create and populate an array of type
Dog…then clone dog…
the arrays refer to the same elements…
This means if we modify an object accessed through the cloned array, the changes will be reflected when we access the same object in the source array, since they point to the same reference.
However, changes to the array itself will only affect that array.
If you generally understand how object references work, it is easy to understand how arrays of objects are impacted by cloning and modifications. To gain further insight into references and primitives I would suggest reading this excellent article.
Gist of Source Code