0

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);
    } 
Dr Mido
  • 2,414
  • 4
  • 32
  • 72

2 Answers2

1

The second version is correct. The constructor calls p.getApps(), which returns a copied array.

The third version would copy the array two times. That is needless.

Dorian Gray
  • 2,913
  • 1
  • 9
  • 25
-1

Objects are passed by reference in java e.g. String, Integer, Float etc. Only primitive types are passed by value e.g. int, long, float, double, char etc.

You could do what you're doing, or use;

System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length) more info: https://docs.oracle.com/javase/7/docs/api/java/lang/System.html

J.Johnson
  • 89
  • 1
  • 1
  • 8
  • 1
    "Java is always pass by value, with no exceptions, ever." - https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value – daniu Jun 05 '19 at 11:14