2014-11-23 57 views
-2

为什么不能正常工作,但是当我将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++) 
     { 
      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; 
    } 

} 

回答

0

因为你正在改变列出哪些是内部的方法在示例中或更新原始列表本身

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; 
} 
1

reverse方法的可变list只存在该方法的寿命。您需要返回新的反向列表并将其分配给一个变量(如下所示),或者修改原始列表本身(Elliott Frisch的答案)。

public class ReverseArray { 
    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] + " "); 
     } 
    } 

    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]; 
     } 
     return temp; 
    } 
} 
2

因为你不能从你的方法更新调用者数组引用(你不需要)。相反,遍历列表中途,与位置就像掉每一个元素,

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; 
    } 
} 

此外,您可以用Arrays.toString(int[])

public static void main(String[] args) { 
    int[] list = { 1, 2, 3, 4, 5 }; 
    reverse(list); 
    System.out.println(Arrays.toString(list)); 
} 

输出是

[5, 4, 3, 2, 1] 
0

打印您阵列您应该从您的方法返回一个值,例如

public static int[] reverse(int[] list) { 
    ... 
    return temp; 
} 
01 reverse.Instead你应该已经返回更新列表,表示的H

,并在主...

list = reverse(list); 

,而不是

reverse(list);