【问题标题】:How to clone/copy an instance of my own class?如何克隆/复制我自己的类的实例?
【发布时间】:2016-05-31 10:29:55
【问题描述】:

这种使用clone的方式正确吗?我每次都会遇到运行时错误。也有人可以建议一种在此类中编写复制构造函数的方法吗?

public class Pair {
    final StringBuffer x;
    final StringBuffer y;

    public Pair(StringBuffer x, StringBuffer y) {
        this.x = x;
        this.y = y;
    }

    public StringBuffer getX() {
        return x;
    }

    public StringBuffer getY() {
        return y;
    }

    public Pair clone() {
        Pair p = new Pair(new StringBuffer(), new StringBuffer());
        try {
            p = (Pair) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new Error();
        }
        return p;
    }
}

【问题讨论】:

  • 标题和标签中提到的arraylist在哪里?
  • 当你忽略它的作用时,为什么你有一个复制构造函数?

标签: java deep-copy


【解决方案1】:

复制构造函数:

public Pair(Pair other) {
  this.x = new StringBuffer(other.x.toString());
  this.y = new StringBuffer(other.y.toString());
}

你应该avoid using clone():

  • clone 在所有情况下都很难正确实施,几乎到了病态的地步
  • 复制对象的重要性将始终存在,因为对象字段通常需要进行防御性复制
  • 复制构造函数和静态工厂方法提供了克隆的替代方法,并且更容易实现

【讨论】:

  • 另外,clone 的原生实现只会给你一个浅拷贝。
猜你喜欢
  • 1970-01-01
  • 2012-01-16
  • 2017-05-19
  • 2012-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-09
相关资源
最近更新 更多