Reputation: 401
For example
int[] test = new int[]{1,2,3};
and I want to clone it (deep copy)
int[] another = test.clone();
What is Java really doing here? Is it copying all the elements individually (O(n)) or something else?
Upvotes: 0
Views: 138
Reputation: 4723
When you clone an array, you need to read each element at least once. You cannot skip the reading of some elements with some clever algorithm. If you want to clone an element, you have to read it. This is inherently O(n).
The Object#clone
method
[...] creates a new instance of the class of this object and initializes all its fields with exactly the contents of the corresponding fields of this object, as if by assignment; the contents of the fields are not themselves cloned. Thus, this method performs a "shallow copy" of this object, not a "deep copy" operation.
In other words, this method copies values. When you have an int[]
, the values are copied and assigned to the new array. When you have an Object[]
, still, the values are copied and assigned. Keep in mind that a reference is just a value as well.
The content of an int[]
are the integer values. Thus, you can change a cloned array without affecting the original array. The content of an Object[]
are references. A cloned reference will still point at the same object. Thus, if you access an object in the cloned array, you will access the same object that is referenced in the original array as well.
Upvotes: 1