为什么我们在Java中使用clone()方法?

Abh*_*sek 29 java clone

为什么我们clone()在Java中使用该方法?(请给出关于内存约束的答案.)这会减少内存使用量吗?如果是,那怎么样?那会降低内存泄漏的影响吗?

And*_*s_D 19

除了不使用clone,实现一个复制构造函数,你询问了内存约束.

克隆的想法是创建克隆对象的精确副本.因此,在最坏的情况下,之后使用两倍的内存量.实际上 - 少一点,因为字符串经常被实习并且(通常)不会被克隆.即使它取决于克隆方法/复制构造函数的实现者.

这是一个带有复制构造函数的类的简短示例:

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]);
  }
}
Run Code Online (Sandbox Code Playgroud)

用法:

Sheep dolly = getDolly();  // some magic to get a sheep
Sheep dollyClone = new Sheep(dolly);
Run Code Online (Sandbox Code Playgroud)


Pét*_*rök 14

我们应该使用它.它是一个破碎而过时的习惯用法,应该在新代码中避免使用.最好尽可能使用复制构造函数.


Jai*_*tel 8

clone()将对象的值复制到另一个对象. clone()方法保存额外的处理任务,以创建对象的精确副本.

正如您在下面的示例中所看到的,两个引用变量具有相同的值.

class Student18 implements Cloneable {

    int rollno;
    String name;

    Student18(int rollno, String name) {

        this.rollno = rollno;
        this.name = name;
    }

    public static void main(String args[]) {

        try {
            Student18 s1 = new Student18(101, "amit");

            Student18 s2 = (Student18) s1.clone();

            System.out.println(s1.rollno + " " + s1.name);
            System.out.println(s2.rollno + " " + s2.name);

        } catch (CloneNotSupportedException c) {
        }

    }

    public Object clone() throws CloneNotSupportedException {

        return super.clone();
    }
} 
Run Code Online (Sandbox Code Playgroud)

输出:

101 amit
101 amit
Run Code Online (Sandbox Code Playgroud)

如果我们通过new关键字创建另一个对象并将另一个对象的值分配给该对象,则需要对该对象进行大量处理.因此,为了保存额外的处理任务,我们使用clone()方法.