java - How to initialize an array in the constructor? -


lets have these 2 different constructors. different between first 1 , second one. how way it? explain difference please! (i know cant have these 2 constructors in same class, show mean.

public class stackoverflow {  private int[] x; // instance variable   stackoverflow(int[] x) { // constructor     this.x=x;      }  stackoverflow(int[] x) { // constructor      this.x = new int[x.length];     for(int k=0 ; k < x.length; k++) {         this.x[k]=x[k];     }                   }          

the first constructor assigns reference of existing int array member variable. caller of constructor can later change array , change reflected in instance.

the second constructor copies array, later changes in passed array wouldn't change copy stored in instance.

int[] intarray = new intarray {1,2,3};  stackoverflow so1 = new stackoverflow(intarray); // assume using first constructor   intarray[1]=5; // changes array stored in `so1` object  stackoverflow so2 = new stackoverflow(intarray); // assume using second constructor  intarray[1]=8; // doesn't change array stored in `so2` object 

Comments

Popular posts from this blog

java - How to specify maven bin in eclipse maven plugin? -

Error while updating a record in APEX screen -

c++ - In an add-in in Excel, written in C(++), how does one get the name of the function which called into the addin? -