【发布时间】:2019-08-21 22:23:12
【问题描述】:
我想在类的复制构造函数中传递一个字符串数组作为参数。我想知道在面向对象的 Java 编程设置中,这些方式中的哪一种是正确/常用的方式:
-在复制构造函数中复制数组 - 在被复制对象的“getArray”方法中复制数组 -以上两种
我的目标是通过值而不是通过引用来复制数组以保持封装。
String[] apps;
// First version
public Smartphone(Smartphone p)
{
this.apps = Arrays.copyOf(p.getApps(), p.getApps().length);
}
public String[] getApps()
{
return apps;
}
// Second version
public Smartphone(Smartphone p)
{
this.apps = p.getApps();
}
public String[] getApps()
{
return Arrays.copyOf(apps, apps.length);
}
// Third version
public Smartphone(Smartphone p)
{
this.apps = Arrays.copyOf(p.getApps(), p.getApps().length);
}
public String[] getApps()
{
return Arrays.copyOf(apps, apps.length);
}
【问题讨论】:
标签: java arrays oop constructor encapsulation