在接收数组的方法中分配两个数组,但是内容未更改,为什么
public class Sol {
public static void main(String[] args) {
int[] list = {1, 2, 3, 4, 5};
reverse(list);
for (int i = 0; i < list.length; i++)
System.out.print(list[i] + " ");// here it prints after reversing 1 2 3 4 5 why?
}
public static void reverse(int[] list) {
int[] array = new int[list.length];
for (int i = 0; i < list.length; i++)
array[i] = list[list.length - 1 - i];
list = array;// is it call by value //here assignment why does not change the contents after exit from the method
}
}
Java对于原始类型按值传递,对于对象按引用传递。请参阅下面的链接以获取更多详细信息。
http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.4.1
public static void main(String[] args) {
int[] list = { 1, 2, 3, 4, 5 };
list = reverse(list);
for (int i = 0; i < list.length; i++)
System.out.print(list[i] + " "); // here it prints after reversing 1 2 3 4 5 why? }
}
public static int[] reverse(int[] list) {
int[] tempList = new int[list.length];
for (int i = 0; i < list.length; i++)
tempList[i] = list[list.length - 1 - i];
return tempList;
}
int[] list = {1, 2, 3, 4, 5};
**reverse(list);**
for (int i = 0; i < list.length; i++)
System.out.print(list[i] + " ");// here it prints after reversing 1 2 3 4 5 why? }
public static void reverse(int[] list) {
int[] new List = new int[list.length];
for (int i = 0; i < list.length; i++)
new List[i] = list[list.length - 1 - i];
list = new List;}
}
在此之后,您没有将反向数组分配给任何变量。这就是这个问题的原因。像这样更改并检查列表=反向(列表);