我知道这是非常基本的,但我不知道为什么我的代码不起作用。下面的代码应该反转数组,但我很想知道为什么输出保持不变!任何解释将不胜感激:))
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;
}
}
答案 0 :(得分:1)
您必须根据以下内容修改方法:
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;
}
}
要查找有关此内容的更多详细信息,请阅读Java中有关按值传递和按引用传递的更多信息。