0

Deep copy of an array

I have a method where I'm trying to return a deep copy of an array . I want to use clone. But I'm not sure if this is the way to go. Will this code do the job?? Any suggestions would be appreciated https://code.sololearn.com/c55uc0752qNo/?ref=app

16th Feb 2021, 5:00 AM
Sattar
Sattar - avatar
1 Antwort
+ 1
it works this way for String[] and Java standard types public String[] getValues(){ return values.clone(); } but not for custom classes like here import java.util.Arrays; class ObjString { String value; public String toString() { return value; } } public class CopyValues { private ObjString[] values; CopyValues( String[] data) { values = new ObjString[data.length]; for (int i=0; i < data.length; i++) { values[i] = new ObjString(); values[i].value = data[i]; } } public ObjString[] getValues() { return values.clone(); } public static void main(String[] args) { String[] data = {"AA","BB","CC","DD","EE"}; CopyValues p = new CopyValues(data); ObjString[] aCopy = p.getValues(); //test p.values[0].value = "XX"; System.out.println( Arrays.toString(p.values) ); // XX changed System.out.println( Arrays.toString(aCopy) ); // XX too, because it is same object } }
17th Feb 2021, 11:05 AM
zemiak