1

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();
    }
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
nutellafella
  • 135
  • 1
  • 4
  • 17

2 Answers2

3

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

Taymon
  • 24,950
  • 9
  • 62
  • 84
1

The reason that your code isn't working is the line:

String [] result = new String(original.length);  

result is an array of Strings, but you're trying to instantiate a single String. The error that the JVM is throwing should have pointed you to this line.

However, this has nothing to do with deep copying. For that, take a look at

Deep copy, shallow copy, clone

Community
  • 1
  • 1
Dancrumb
  • 26,597
  • 10
  • 74
  • 130