0

Cloning the String arrays, using clone() method on java array. After cloning I'm expecting to have new Strings in new array - with new addresses allocated for them. But... I got a bit different behavior, plz look at this:

(It will print:

same address
One

)

public class ArrayCopyClone {

    static String[] array2 = new String[] {"One", "Two", "Three"};

    public static void main(String[] args) {

        String[] copy2 = array2.clone();

        if (copy2[0] != array2[0])  {
            System.out.println("good");   // will never show up
        } else {
           System.out.println("same address");  // I'm expecting never be here
        }

        array2[0] = "new";

        System.out.println(copy2[0]); // "One", and this is OK (it means we have a copy)

    }

}

Is it related to string-shadowing? Should it be?

ses
  • 13,174
  • 31
  • 123
  • 226

2 Answers2

1

Cloning an array gives a shallow copy. So the contents are identical. For deep cloning see here.

Community
  • 1
  • 1
sbk
  • 3,856
  • 1
  • 19
  • 19
0

First, by default clone() is not implemented as a "deep clone", so it copies sub-objects as references. Moreover strings are cached by JDK. You are exposing 2 these effects.

AlexR
  • 114,158
  • 16
  • 130
  • 208
  • 2
    I don't think string caching comes into play in this example; any other type of object in the arrays would exhibit the same effect. – Michael Myers Feb 12 '13 at 16:10