java - Is there any advantage of using array.clone() above manual copy -


are there drawbacks or advantages of using

public loteria( int[] liczby) {    this.liczby = liczby.clone(); } 

instead of:

public loteria( int[] liczby) {    this.liczby = new int[liczby.length];    for(int = 0....)        this.liczby[i] = liczby[i]; } 

both approaches create shallow copies of array elements, means elements inside arrays still reference each other. if want shallow copies, stick array.clone().

  • more readable
  • less code, uses standard java api.

deep copying arrays

java 6+

this.liczby = arrays.copyof(liczby, liczby.length); 

older versions

system.arraycopy(liczby, 0, this.liczby, 0, liczby.length); 

test

object[] original = { new object(), null }; object[] copy = new object[2]; system.arraycopy(original, 0, copy, 0, original.length); object[] copy2 = arrays.copyof(original, original.length + 1); copy2[1] = 2; system.out.println(original[1]); // null system.out.println(copy2[1]); // 2 

Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -