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.
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.
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.