I've learnt that for arrays the clone
method is well-behaved and we can use it. But I thought that the type of the elemetns the arrays hold should have implemented Cloneable
interface. Let me provide some example:
public class test {
public static void main(String[] args){
Test[] arr_t = new Test[1];
arr_t[0] = new Test(10);
Test[] an_arr = arr_t.clone();
an_arr[0]= new Test(5);
System.out.println(an_arr[0].test); //5
System.out.println(arr_t[0].test); //10
}
public static class Test{
public int test;
public Test(int test) {
this.test = test;
}
}
}
I thought that 5 should have been printed twice. The reason for that is by clonning arrays we're creating new arrays containing references to the objects the first array holded (Because the type of the elemnts does not implement Cloneable
). Couldn't you straighten the things out?
It's not clear if it's neccesary the array element's type implements Cloneable
.
It's a simple concept, but seems hard to explain. When you clone the array, you will have two district arrays in memory, but with the same values in their indexes.
In your second array
an_arr
doingan_array[0] = new Test(5)
you will put another reference in the slot 0.But the index 0 of the clone is in a different place from the cloned array.
Your example is valid if you do
Now both will print the same value because they hold the same reference to the same object, but the place where this reference is stored, is different.