Java implements an array inversion method instance
- 2020-06-23 00:17:20
- OfStack
The method of array flip (java implementation), array flip, is to invert the array, for example, the original array is: {"a","b","c","d"}, then the flipped array is {"d","c","b","a"}.
[Method 1] Use a collection of tool classes: Collections. reverse(ArrayList) to reverse the array:
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(" Pre-reverse sort : " + arrayList);
Collections.reverse(arrayList);
System.out.println(" Reverse sort : " + arrayList);
}
}
The output result of the above code operation is:
Sort before reversal: [A, B, C, D, E]
Reverse ordering: [E, D, C, B, A]
[Method 2] Use the set ArrayList to implement inversion:
[Method 3] Invert the array directly, that is, the first element of the inverted array is equal to the last element of the source array:
The implementation codes for methods 2 and 3 are as follows:
package javatest2;
import java.util.ArrayList;
public class JavaTest2 {
public static void main(String[] args) {
String[] Array = { "a", "b", "c", "d", "e" };
reverseArray1(Array);// Using the collection ArrayList Implement reverse
for (int j = 0; j < Array.length; j++) {
System.out.print(Array[j] + " ");
}
System.out.print("\n");
String[] temp = reverseArray2(Array);// Invert directly using an array
for (int j = 0; j < temp.length; j++) {
System.out.print(Array[j] + " ");
}
}
/*
* Function: reverseArray1 and reverseArray2
* Function: Implementation The array to flip
* Such as: {'a','b','c','d'} become {'d','c','b','a'}
*/
private static void reverseArray1(String[] Array) {
ArrayList<String> array_list = new ArrayList<String>();
for (int i = 0; i < Array.length; i++) {
array_list.add(Array[Array.length - i - 1]);
}
Array = array_list.toArray(Array);
}
private static String[] reverseArray2(String[] Array) {
String[] new_array = new String[Array.length];
for (int i = 0; i < Array.length; i++) {
// Inverted array of the first 1 The elements are equal to the end of the source array 1 An element:
new_array[i] = Array[Array.length - i - 1];
}
return new_array;
}
}