Home > Java > javaTutorial > How to flip an array in java

How to flip an array in java

王林
Release: 2023-05-01 14:19:06
forward
1620 people have browsed it

1. Use Collections.reverse(arrayList)

import java.util.ArrayList;
import java.util.Collections;
 
public class ArrayReversal {
 
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("反转前的顺序:"+arrayList);
Collections.reverse(arrayList);
System.out.println("反转后的顺序:"+arrayList);
}
 
}
Copy after login

2. Flashback loop

Re-assign a new array , for example

private static String[] reverseArray(String[] Array) {  
        String[] new_array = new String[Array.length];  
        for (int i = 0; i < Array.length; i++) {  
            // 反转后数组的第一个元素等于源数组的最后一个元素:  
            new_array[i] = Array[Array.length - i - 1];  
        }  
        return new_array;  
    }
Copy after login

3. Use temporary array

    /**
     * 方法一:使用临时数组
     */
    @Test
    public void method1(){
        int[] array = new int[5];
        System.out.println("【方法一】:\n数组的元素为");
        for (int i=0;i<array.length;i++){
            array[i] = (int) (Math.random()*100);
            System.out.print(array[i]+" ");
        }
        System.out.println();
        System.out.println("数组反转后的元素为");
        //准备临时数组
        int[] temp = new int[array.length];
        //把原数组的内容反转后赋值给数组temp
        for (int i=0;i<array.length;i++){
            temp[i] = array[array.length-i-1];
        }
        //由于要求是对原数组array实现反转效果,所以再把temp挨个赋值给array
        for (int i=0;i<temp.length;i++){
            array[i] = temp[i];
            System.out.print(array[i]+" ");
        }
    }
Copy after login

The above is the detailed content of How to flip an array in java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template