Search code examples
javaclone

Clonning String array, checking the refs


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?


Solution

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