为什么我们在Java中使用clone()方法? [英] Why do we use the clone() method in Java?

查看:129
本文介绍了为什么我们在Java中使用clone()方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Why do we use the clone() method in Java? (Please give the answer in respect of memory constraint.) Will that reduce memory usage? If yes, then how? Will that reduce the effect of memory leak?

推荐答案

除了不使用clone,实现一个拷贝构造函数,你问过内存限制。

Apart from do not use clone, implement a copy constructor, you asked about memory constraints.

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

The idea of cloning is to create an exact duplicate of the cloned object. So in worst case, you use twice the amount of memory afterwards. Practically - a bit less, because Strings are often interned and will (usually) not be cloned. Even though it's up to the implementor of the clone method/copy constructor.

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

Here's a short example of a class with a copy constructor:

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);

这篇关于为什么我们在Java中使用clone()方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆