Search code examples
javacopy

Basic Deep Copy, Java


Okay, so i know there is a million questions out there on deep copy but i still have a hard time understanding because there is all this talk about cloning and serialization and what not. When making a deep copy of a String[] array is this how you would do it in a very simple way? without validating.

public String[] copyString(String[] others)
  {
    String[] copy = new String[others.length];
    for (int i = 0; i < others.length; i++)
    {
      copy[i] = others[i];
    }

    return copy;
  }

Solution

  • When making a deep copy of a String[] array is this how you would do it in a very simple way?

    Yes.

    You need to

    1. allocate a new object
    2. deep-copy the contents from the source object

    and that's exactly what your method does.

    Note that this only works because String is immutable, otherwise you would be performing a shallow copy of the contents.