除了不使用克隆,实现一个复制构造函数,你询问了内存限制。
克隆的想法是创建一个完全重复的克隆对象。所以在最坏的情况下,你以后使用两倍的内存量。实际上 – 一点点,因为字符串通常被实习,并将(通常)不被克隆。即使由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 sheep
Sheep dollyClone = new Sheep(dolly);