0

I know this is pretty basic, but I don't know why my code doesn't work. The code below is supposed to reverse the array, but I'm seriously dying to know why the output stays the same! Any explanation will be appreciated :)

public class Test {
    public static void main(String[] args) {
        int[] oldList = {1, 2, 3, 4, 5};
        reverse(oldList);
        for (int i = 0; i < oldList.length; i++)
            System.out.print(oldList[i] + " ");
    }
    public static void reverse(int[] list) {
        int[] newList = new int[list.length];
        for (int i = 0; i < list.length; i++)
            newList[newList.length] = list[list.length - 1 - i];
        list = newList;
    }
}
Jordan
  • 71
  • 5

1 Answers1

1

You will have to modify the method according to the following:

public class Test {
    public static void main(String[] args) {
        int[] oldList = {1, 2, 3, 4, 5};
        oldList = reverse(oldList); //assign the returned value from the method
        for (int i = 0; i < oldList.length; i++)
            System.out.print(oldList[i] + " ");
    }
    public static int[] reverse(int[] list) {
        int[] newList = new int[list.length];
        for (int i = 0; i < list.length; i++)
            newList[newList.length] = list[list.length - 1 - i];
        list = newList;
        return list;
    }
}

To find more details about this read more about pass by value and pass by reference in Java.

Pritam Banerjee
  • 17,953
  • 10
  • 93
  • 108