[英]Time complexity of clone method in Java?
Every object has clone() method in Java.每个 object 在 Java 中都有 clone() 方法。
What's the time complexity of the clone method in following condiction:以下条件下克隆方法的时间复杂度是多少:
I just have a guess wheter the build-in clone method use some technique to decrease the time complexity into O(1).我只是猜测内置克隆方法是否使用某种技术将时间复杂度降低到 O(1)。
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.
这意味着它会克隆 object 中的所有值和引用,但不会克隆“子”对象,例如 arrays 和引用的对象。 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)
.浅克隆操作本质上是
O(1)
。 If you want to talk O(n)
, that would be cloning a collection of objects.如果你想谈论
O(n)
,那就是克隆一个对象集合。 Counting the fields is not meaningful from a Big O perspective, because the number of fields for a given object does not vary.从 Big O 的角度来看,计算字段数没有意义,因为给定 object 的字段数没有变化。 In other words, the clone for a given object always takes the same amount of time (constant time) to execute (more or less).
换句话说,给定 object 的克隆总是花费相同的时间(恒定时间)来执行(或多或少)。
Further Reading延伸阅读
Clone() method in Java Java 中的 Clone() 方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.