Home >Java >javaTutorial >How to flip an array in java
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); } }
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; }
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]+" "); } }
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!