I want to pass a string array as a parameter in the copy constructor of a class. I want to know which of these ways is the correct/usual way in an Objects Oriented Java programming setting:
-Copying the array inside the copy constructor -Copying the array inside the "getArray" method of the object being copied from -Both of the above
My goal is to copy the array by values and not by reference to keep encapsulation.
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);
}