Java Examples - Array Reversal

Java 实例Java Examples

In the following example, we use a custom reverse method to reverse the array:

Example 1

public class ExampleTest {
 
    /* Reverse the array */
    static void reverse(int a[], int n)
    {
        int[] b = new int[n];
        int j = n;
        for (int i = 0; i < n; i++) {
            b[j - 1] = a[i];
            j = j - 1;
        }
 
        /* Input the array to reverse */
        System.out.println("The reversed array is:\n");
        for (int k = 0; k < n; k++) {
            System.out.println(b[k]);
        }
    }
 
    public static void main(String[] args)
    {
        int [] arr = {10, 20, 30, 40, 50};
        reverse(arr, arr.length);
    }
}

The output of running the above code is:

反转后数组是: 

50
40
30
20
10

Example 2

public class ExampleTest {
 
    /* Create a method that swaps the first with the last, the second with the second-to-last, and so on */
    static void reverse(int a[], int n)
    {
        int i, k, t;
        for (i = 0; i < n / 2; i++) {
            t = a[i];
            a[i] = a[n - i - 1];
            a[n - i - 1] = t;
        }
 
        System.out.println("The reversed array is:\n");
        for (k = 0; k < n; k++) {
            System.out.println(a[k]);
        }
    }
 
    public static void main(String[] args)
    {
        int [] arr = {10, 20, 30, 40, 50};
        reverse(arr, arr.length);
    }
}

The output of running the above code is:

反转后数组是: 

50
40
30
20
10

Example

import java.util.*;
 
public class ExampleTest {
 
    /* Use the java.util.Arrays.asList(array) method */
    static void reverse(Integer a[])
    {
        Collections.reverse(Arrays.asList(a));
        System.out.println(Arrays.asList(a));
    }
 
    public static void main(String[] args)
    {
        Integer [] arr = {10, 20, 30, 40, 50};
        reverse(arr);
    }
}

The output of running the above code is:

[50, 40, 30, 20, 10]

Java 实例Java Examples

Other Extensions