Java parameter value changes itself -


Today, while writing a simple program, I found some weird behavior. I have written a simple sorting method that gives an array of another array.

  public double [] sortime (double [] array) {double] narray = new double [array.length]; Narray = array; For (int i = 0; i & lt; narray.length; i ++) {for (int j = 0; j & lt; narray.length; j ++) {if (narray [i] & lt; Narray [j]) {double temp = narray [i]; narray [i] = narray [ja]; Narray [ja] temporary =; }}} / TODO automatically returns the generated method stub; }   

In my driver class, when I told this sort my method, it also updated my test diagram as testArray is out of scope for sortmeme method, then when test array Has been sorted?

  double [] testArray = {3, 6, 2, 5, 8, 4, 1, 7}; Double [] results; Results = Apestorts (testers); Af.printMe (results);    

In your sorting method, you specify the context Using array to narrey using narray = array; .

This means that narrey is pointing the same code as array , and so if you go to narrey If you modify, then the array is also changed and because the method has the reference to testArray in the array, testArray is also sorted.

If you do not want to change the testArray, use system.arraycopy () while specifying array to narre . narre to copy the values ​​of array . Change it as shown below.

  System Arrayopy (array, 0, array, 0, array. Length);    

Comments

Popular posts from this blog

Pass DB Connection parameters to a Kettle a.k.a PDI table Input step dynamically from Excel -

multithreading - PhantomJS-Node in a for Loop -

c++ - MATLAB .m file to .mex file using Matlab Compiler -