-3

Is this way of using clone correct? I am getting a runtime error every time. Also can anybody suggest a way to write copy constructor in this 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;
    }
}
Tom
  • 16,842
  • 17
  • 45
  • 54
Learning
  • 89
  • 11

1 Answers1

3

A copy constructor:

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

You should 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
Andy Turner
  • 137,514
  • 11
  • 162
  • 243