I’m trying to experiment with deep copying since our professor told us to do so. He gave us a snippet of codes but once I typed it in netbeans, it won’t work…
Could someone help me explain the concept of deep copy through these codes?
int i;
String [] original = {"Aref","Ali","Emad","Sami"};
String [] result = new String(original.length);
for(i=0;i<original.length;i++){
result[i] = (String) original[i].clone();
}
A deep copy is a copy of an object that, in addition to copying the object’s individual fields, also goes through all the other objects that those fields refer to and copies them. This ensures that if one of those objects is modified through one copy, the other copy is unaffected.
This code makes a deep copy of
originalby first creating a new array, then iterating through it, making a copy of each string referred to in the array, and putting a reference to the newly copied string in the new copy of the array. Or at least, that’s what it would do if not for the typo that others have mentioned.Note that this is pointless in this particular case, since Java strings are immutable and therefore there is no danger of the referred object being modified.