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

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -