Java 在接收数组的方法中分配两个数组
在一个方法中分配两个数组,该方法接收一个数组,但其内容未更改,为什么Java 在接收数组的方法中分配两个数组,java,arrays,reference,call,Java,Arrays,Reference,Call,在一个方法中分配两个数组,该方法接收一个数组,但其内容未更改,为什么 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]
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; here is the problem // is it call by value //here assignment why does not change the contents after exit from the method
i do not ask about call by reference and i do not need answers for the code
i need to understand this statement (list = array; why is it call by value when exiting from the method reversing disappeared)
}
}
公共类Sol{
公共静态void main(字符串[]args){
int[]list={1,2,3,4,5};
反向(列表);
for(int i=0;i
Java是原语类型的按值传递和对象的按引用传递。
有关更多详细信息,请参阅以下链接
publicstaticvoidmain(字符串[]args){
int[]list={1,2,3,4,5};
列表=反向(列表);
for(int i=0;i
int[]list={1,2,3,4,5};
**反向(列表)**
for(int i=0;i
在这种情况下,在反转数组之后,您没有将反转的数组分配给任何变量。这就是这个问题的原因。换成这样,检查一下
列表=反向(列表)在反转1 2 3 4 5后打印,为什么?你认为逆向(列表)是什么代码>是否(如果转录正确)?是否使用?
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;}
}