0
class X{

    private String[] filename;

    public X(String[] filename){
        this.filename = filename.clone();
    }
}

Is calling clone() is good option when local variable and instance variable is same in constructor.

D. Lawrence
  • 943
  • 1
  • 10
  • 23
  • What do you mean by same? Same Object Instance? – Gaurav Jeswani Dec 16 '19 at 10:31
  • What are you achieving out of this? A parameter can be directly assigned to the class variable! – Sandeep Kumar Dec 16 '19 at 10:31
  • you should understand this has no influence at all. Yes, they have the same name, but only if you use them through the (this.) reference, it's the instance variable – Stultuske Dec 16 '19 at 10:33
  • 1
    It is no better or worse than other options. (The fact that your field name and local variable name are the same make zero difference. Why would it?) – Stephen C Dec 16 '19 at 10:34
  • That's one of the reasons for this `this`-operator... If a variable name is ambiguous, you can distinguish by `this` (in case one of them is a class attribute and the other one a parameter): `this.filename = filename;`, no need for cloning... – deHaar Dec 16 '19 at 10:37

1 Answers1

0

This depends on what you actually want to achieve. Since the argument filename is in fact a reference to the object that the caller created, whoever called new X(filename) has a reference to the filename array and can further modify it.

1) If you don't mind that code outside your control can change the array, you can just assign this.filename = filename.

2) If you want to make sure no other code can mess up with your array than cloning can help. Keep in mid though the new array will still hold reverences to the very same objects the original one had. Thus it will not help much if the array elements are mutable. For example if you had Foo[] instead of String[], someone having a reference to any given Foo can modify it outside of your control.

3) If by any chance you decided to use a single element array instead of String only because arrays have the clone method, then your approach does not buy you anything.

Milen Dyankov
  • 2,972
  • 14
  • 25
  • 1
    *"Arguments are passed by reference"* — this is somewhat inaccurate in the context of Java. [Java is always pass-by-value](https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value) – it's just that the values themselves are references. – MC Emperor Dec 16 '19 at 12:14
  • I didn't mean to claim Jawa is "pass-by-reference". But I see how my answer can be misinterpreted this way so I updated it. Hope it's more clear now. Thanks for pointing it out. – Milen Dyankov Dec 16 '19 at 13:15
  • This looks better to me :-) – MC Emperor Dec 16 '19 at 13:18
  • If you don't mind that code outside your control can change the array, you can just assign this.filename = filename. -- if I go with this option its showing 1 vulnerabilities in sonar. – Nisha Gupta Dec 17 '19 at 06:13