除了 不使用克隆外,还实现一个复制构造函数 ,您询问了内存限制。
克隆 的想法是创建克隆对象的精确副本。因此,在最坏的情况下,此后您将使用两倍的内存量。实际上-
少了一点,因为String经常被嵌入并且(通常)不会被克隆。即使由clone方法/ copy构造函数的实现者来决定。
这是带有复制构造函数的类的简短示例:
public class Sheep { private String name; private Fur fur; private Eye[2] eyes; //... // the copy constructor public Sheep(Sheep sheep) { // String already has a copy constructor ;) this.name = new String(sheep.name); // assuming Fur and Eye have copy constructors, necessary for proper cloning this.fur = new Fur(sheep.fur); this.eyes = new Eye[2]; for (int i = 0; i < 2; i++) eyes[i] = new Eye(sheep.eyes[i]); }}用法:
Sheep dolly = getDolly(); // some magic to get a sheepSheep dollyClone = new Sheep(dolly);



