java - Undesrstanding clone method for arrays -


i've learnt arrays clone method well-behaved , can use it. thought type of elemetns arrays hold should have implemented cloneable interface. let me provide 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;         }     } } 

demo

i thought 5 should have been printed twice. reason clonning arrays we're creating new arrays containing references objects first array holded (because type of elemnts not implement cloneable). couldn't straighten things out?

it's not clear if it's neccesary array element's type implements cloneable.

it's simple concept, seems hard explain. when clone array, have 2 district arrays in memory, same values in indexes.


in second array an_arr doing an_array[0] = new test(5) put reference in slot 0.

but index 0 of clone in different place cloned array.

your example valid if do

test[] arr_t = new test[1]; arr_t[0] = new test(10); test[] an_arr = arr_t.clone();  an_arr[0].test = 5; // here, changed object system.out.println(an_arr[0].test); //5 system.out.println(arr_t[0].test);  //5 

now both print same value because hold same reference same object, place reference stored, different.


Comments

Popular posts from this blog

How has firefox/gecko HTML+CSS rendering changed in version 38? -

android - CollapsingToolbarLayout: position the ExpandedText programmatically -

Listeners to visualise results of load test in JMeter -