CabDude
CabDude

Reputation: 132

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;
  }

Upvotes: 0

Views: 119

Answers (2)

pik4760
pik4760

Reputation: 13

I think you can also use Arrays.copyOf(others,others.length) for a deep copy.

Upvotes: 1

Emil Laine
Emil Laine

Reputation: 42838

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.

Upvotes: 2

Related Questions