-1

Today, while writing a simple program, I found some strange behaviour. I wrote simple sorting method in which returns another sorted array.

public double[] sortMe(double[] array) 
{
    double[] narray=new double[array.length];
    narray=array;
    for(int i=0;i<narray.length;i++)
    {
        for(int j=0;j<narray.length;j++)
        {
            if(narray[i]<narray[j])
            {
                double temp=narray[i];
                narray[i]=narray[j];
                narray[j]=temp;
            }
        }
    }
    // TODO Auto-generated method stub
    return narray;
}

In my driver class, when I called this sortMe method, it updated my testArray as well. Since testArray is out of scope for sortMe method, then when testArray got sorted ?

double [ ] testArray = {3, 6, 2, 5, 8, 4, 1, 7};
double [ ] results;
results = af.sortMe(testArray);
af.printMe(results);
Mukesh Sharma
  • 8,914
  • 8
  • 38
  • 55
  • Please read about 'Pass by Value' and 'Pass by Reference'. That would answer your question. http://stackoverflow.com/questions/373419/whats-the-difference-between-passing-by-reference-vs-passing-by-value – Vivek Viswanathan Apr 22 '14 at 07:07
  • Check this out. http://stackoverflow.com/questions/40480/is-java-pass-by-reference – root Apr 22 '14 at 07:09

2 Answers2

0

In your sortMe method, you are assigning the reference of array to narray using narray=array;.

This means now narray is pointing to the same array as array, and so if you modify narray, array is also changed and since array just has a reference to testArray passed to the method, testArray is also sorted.

If you do not want testArray to change, when assigning the array to narray, use System.arraycopy() to copy the values of array to narray. Change it as shown below.

System.arraycopy(array,0,narray,0,array.length);
anirudh
  • 4,116
  • 2
  • 20
  • 35
0

What do you think these lines do:

double[] narray=new double[array.length];
narray=array;

It creates a new array, which is then immediately discarded, and assigned the same instance as the parameter array.

If you want to return a new array, either use it in a constructor, or manually copy the fields from array A to array B. Since you're doing a sort, you probably don't even need to do this.

Mikkel Løkke
  • 3,710
  • 23
  • 37