Every object has clone() method in Java.
What's the time complexity of the clone method in following condiction:
- Default implementation, do not override clone().
- The Ojbect contains n fields.
I just have a guess wheter the build-in clone method use some technique to decrease the time complexity into O(1).
CodePudding user response:
The base clone method is a shallow copy. That means it clones all of the values and references in the object, but not "child" objects such as arrays and referenced objects. To do that, you need a deep copy.
To create a deep copy, you have to override the clone method and write an implementation yourself, or take advantage of some cloning library that recursively walks all of your members using Reflection.
The shallow clone operation is essentially O(1)
. If you want to talk O(n)
, that would be cloning a collection of objects. Counting the fields is not meaningful from a Big O perspective, because the number of fields for a given object does not vary. In other words, the clone for a given object always takes the same amount of time (constant time) to execute (more or less).
Further Reading
Clone() method in Java