1

I have found several threads how to reverse an array. However, I don't follow why can't use the same code for both a static method and a void method.

Can someone explain the difference in the following examples?

For a static method we can write:

public static double[] reverse (double[] a) 
{
        int n = a.length;
        for (int i = 0; i < n/2; i++) 
        {
            double temp = a[i];
            a[i] = a[n-(i+1)];
            a[n-(i+1)] = temp;
        }
        return a;
}

But for a static void we have:

public static void reverse (double[] a) 
{
    for (int i = 0, j = a.length-1; i < j; i++, j--)
    {
        double temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }
}
JDoeDoe
  • 361
  • 1
  • 2
  • 7

1 Answers1

1

First of all both methods in your case are static. They just have different return type

For the static void reverse (double[] a) case you do like this:

double[] arr = //some array
reverse(arr); //at this point arr is reversed so that you can use it 
reversedArr = arr; //or assign to different variable

Actually its ok if you have to reverse some internal array but I still don't like it because not too obvious the array is changed. I don't think its good to have such a method public...

static double[] reverse (double[] a) is good to be part of some utility class i.e.

double[] arr = //some array
reversedArr = ArrayUtils.reverse(arr); // now you can reuse method and you actually see that you changed the array

But you should modify a method not to change initial array, because you may run into trouble (calling an utility method should not modify the initial value)

Akceptor
  • 1,914
  • 3
  • 26
  • 31