如何 clone/copy 我自己的实例 class?

How to clone/copy an instance of my own class?

这种clone的使用方式是否正确?我每次都会收到运行时错误。还有人可以建议在这个class中编写复制构造函数的方法吗?

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

复制构造函数:

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

你应该avoid using clone():

  • clone is very tricky to implement correctly in all circumstances, nearly to the point of being pathological
  • the importance of copying objects will always remain, since object fields often need to be defensively copied
  • copy constructors and static factory methods provide an alternative to clone, and are much easier to implement