See what is Xiaobai can know how to flip Java arrays

This article mainly introduces the detailed methods of flipping java arrays. The article introduces in detail through the sample code. It has a certain reference learning value for everyone's study or work. Friends who need it will learn together with the editor below. Let's learn

In the elements of the array, sometimes we need to reverse their order to become a new array. There are many mainstream array flipping methods. This article sorts out some practical methods: arrayList, reverse loop, and temporary array. I believe that apart from the first method, you may not have been in contact with the other two. The following three methods of Java array flipping, we will bring examples to explain.

1.使用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. The flashback loop renews
an array for assignment, 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 arrays

/**
  * 方法一:使用临时数组
  */
 @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]+" ");
   }
 }

to sum up

The above is the method of flipping the java array. I believe that after reading the code, you have already started to run the test. Regarding some other common flipping methods, I will not describe them here. If you are interested, you can check it yourself. For more related java array flipping content, please search wx141194356 Remarks (csdn) I hope you will support the editor a lot in the future!

Guess you like

Origin blog.csdn.net/dcj19980805/article/details/115279887