Java 反向数组方法无效
为什么这不起作用,但是当我将for循环从main方法移动到reverse方法时,它起作用了Java 反向数组方法无效,java,Java,为什么这不起作用,但是当我将for循环从main方法移动到reverse方法时,它起作用了 public class ReverseArray { public static void main(String[] args) { int[] list = {1, 2, 3, 4, 5}; reverse(list); for (int i = 0; i < list.length; i++) {
public class ReverseArray
{
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 static void reverse(int[] list)
{
int[] temp = new int[list.length];
for (int i = 0; i < list.length; i++)
{
temp[i] = list[(list.length - 1) - i];
}
list = temp;
}
}
public类reversearlay
{
公共静态void main(字符串[]args)
{
int[]list={1,2,3,4,5};
反向(列表);
for(int i=0;i
反向方法中的变量列表
仅在该方法的生存期内存在。您需要返回新的反向列表并将其分配给变量(下面的示例),或者修改原始列表本身(Elliott Frisch的答案)
public类reversearlay{
公共静态void main(字符串[]args){
int[]list={1,2,3,4,5};
列表=反向(列表);
for(int i=0;i
,因为您无法从方法中更新调用者数组引用(而且不需要)。相反,在列表中迭代一半,并用如下位置交换每个元素:
public static void reverse(int[] list) {
for (int i = 0; i < list.length / 2; i++) {
int t = list[(list.length - 1) - i];
list[(list.length - 1) - i] = list[i];
list[i] = t;
}
}
输出为
[5, 4, 3, 2, 1]
您应该从方法返回一个值,即
public static int[] reverse(int[] list) {
...
return temp;
}
总的来说
list = reverse(list);
而不是
reverse(list);
因为您正在对列表进行更改,而这些更改是该方法的内部更改。相反,您应该返回更新后的列表,如示例中所示,或者更新原始列表本身
public static void main (String[] args) throws java.lang.Exception
{
int[] list = {1, 2, 3, 4, 5};
list=reverse(list);
for (int i = 0; i < list.length; i++)
{
System.out.print(list[i] + " ");
}
}
public static int[] reverse(int[] list)
{
int[] temp = new int[list.length];
for (int i = 0; i < list.length; i++)
{
temp[i] = list[(list.length - 1) - i];
//list[i]=temp[i];
}
list = temp;
return list;
}
publicstaticvoidmain(字符串[]args)抛出java.lang.Exception
{
int[]list={1,2,3,4,5};
列表=反向(列表);
for(int i=0;i
reverse(list);
public static void main (String[] args) throws java.lang.Exception
{
int[] list = {1, 2, 3, 4, 5};
list=reverse(list);
for (int i = 0; i < list.length; i++)
{
System.out.print(list[i] + " ");
}
}
public static int[] reverse(int[] list)
{
int[] temp = new int[list.length];
for (int i = 0; i < list.length; i++)
{
temp[i] = list[(list.length - 1) - i];
//list[i]=temp[i];
}
list = temp;
return list;
}