Java 示例 - 反转数组列表

  • 问题描述

    如何反转数组列表?
  • 解决方案

    以下示例使用 Collections.reverse(ArrayList) 方法反转数组列表。
    
    import java.util.ArrayList;
    import java.util.Collections;
    public class Main {
       public static void main(String[] args) {
          ArrayList arrayList = new ArrayList();
          arrayList.add("A");
          arrayList.add("B");
          arrayList.add("C");
          arrayList.add("D");
          arrayList.add("E");
          System.out.println("Before Reverse Order: " + arrayList);
          Collections.reverse(arrayList);
          System.out.println("After Reverse Order: " + arrayList);
       }
    }
    
  • 结果

    上面的代码示例将产生以下结果。
    
    Before Reverse Order: [A, B, C, D, E]
    After Reverse Order: [E, D, C, B, A]
    
    下面的例子是数组反转的另一个例子。
    
    public class HelloWorld {
       public static void main(String[] args) {
          int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
          System.out.println("Array before reverse:");
          
          for (int i = 0; i < numbers.length; i++) {
             System.out.print(numbers[i] + " ");
          } 
          for (int i = 0; i < numbers.length / 2; i++) {
             int temp = numbers[i];
             numbers[i] = numbers[numbers.length - 1 - i];
             numbers[numbers.length - 1 - i] = temp;
          } 
          System.out.println("\nArray after reverse:");
          for (int i = 0; i < numbers.length; i++) {
             System.out.print(numbers[i] + " ");
          } 
       }
    }
    
    上面的代码示例将产生以下结果。
    
    Array before reverse:
    1 2 3 4 5 6 7 8 9 10 
    Array after reverse:
    10 9 8 7 6 5 4 3 2 1