2016-05-31 95 views
-3

这种使用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; 
    } 
} 
+0

哪里'arraylist'在标题和标签中提到? –

+0

为什么你有一个复制构造函数,当你忽略它的作用? – Tom

回答

3

拷贝构造函数:

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

您应该avoid using clone()

  • clone是非常棘手的在任何情况下都正确地执行,几乎要被病理
  • 复制对象的重要性将永远保持,因为对象字段经常需要防守复制
  • 拷贝构造函数和静态工厂方法提供替代克隆,并且更容易实现
+1

另外,'clone'的本地实现只会给你一个浅拷贝。 –