0
public class Reverse {

public static void main(String[] args) {
    String [] simpsons = {"Homer", "Flanders", "Apu"};
    reverse(simpsons);
    System.out.println(simpsons[0] + " " + simpsons[1] + " "
            + " " + simpsons[2]);


} //End main

public static void reverse(String[] list)
{
    String[] temp = new String[list.length];
    for (int i =0; i<list.length; i++)
    {
        temp[i] = list[list.length-i-1];
    }
    //System.arraycopy(temp, 0 , list, 0, list.length);
    list = temp;;
}

}    

I'm just getting started in Java, and this problem confused me. As you can see, I've solved the problem with the commented out arraycopy method. I'm simply confused as to why the list = temp still returns the original, non-reversed array. I believe I understand conceptually that references are just locations in memory, but doesn't list = temp assign the passed in array to the memory location of temp, AKA the reversed array?

user2864740
  • 60,010
  • 15
  • 145
  • 220

2 Answers2

1

Because you can't update the caller's reference in the called method (the change is local) and arrays are immutable. Just return the new reference and update it in the caller.

public static String[] reverse(String[] list) {
  String[] temp = new String[list.length];
  for (int i = 0; i < list.length; i++) {
    temp[i] = list[list.length - i - 1];
  }
  return temp;
}

Then in main()

simpsons = reverse(simpsons);

When I run it, I get the expected output

Apu Flanders  Homer

Or, on further consideration you could be efficient and reverse() the array in place -

public static void reverse(String[] list) {
  for (int i = 0; i < list.length / 2; i++) {
    String t = list[list.length - i - 1];
    list[list.length - i - 1] = list[i];
    list[i] = t;
  }
}

Which also works here.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

Method arguments in java are local scope, so while the variable is a reference to your list passed in, that variable holding the reference is local to your reverse method, reassigning the reference to temp is only within local scope.

A better implementation would swap last and first, then last-1,first+1 etc. this way you are modifying the passed array and also do not need a second temp array, just a single temp variable of the array type.

Brett Ryan
  • 26,937
  • 30
  • 128
  • 163