Array traversal and inversion

1. Elegant traversal of arrays

In the process of learning java, the most common problem encountered is how to print out an array traversal. Here are three of the more commonly used methods that I know of. Assume that what needs to be traversed is arr, and the elements inside are {1, 4, 5, 7, 11}.

1.1 for loop traversal

for (int i = 0; ; ++i){
    
    
	if(i == arr.length - 1){
    
    
	    System.out.print(arr[i]);
	    break;
	}
    System.out.print(arr[i] + ",");
}

1.2 foreach traversal

for(int x : arr){
    
    
	System.out.println(x);
}

1.3 Arrays tool class traversal

public class Main {
    
    
    public static void main(String[] args) {
    
    
        int[] ns = {
    
     1, 2, 3, 4 };
        System.out.println(Arrays.toString(ns));
    }
}
import java.util.Arrays;

public class Main {
    
    
    public static void main(String[] args) {
    
    
        int[][] ns = {
    
    
            {
    
     1, 2, 3, 4 },
            {
    
     5, 6, 7, 8 },
            {
    
     9, 10, 11, 12 }
        };
        System.out.println(Arrays.deepToString(ns));
    }
}

2. Array inversion

The easiest way to perform array inversion is to create a new array, and then traverse the array elements in reverse order and put them into the new array. The following piece of code is to traverse the reversed array without creating a new array, and the space efficiency will be higher.

public class ReverseArr {
    
    
    public static void main(String[] args) {
    
    
        int[] arr = {
    
    15,21,6,7,8};
        //写法1:
//        for (int i = 0; i < arr.length/2; i++) {
    
    
//            int temp = arr[i];
//            arr[i] = arr[arr.length - i - 1];
//            arr[arr.length-i-1] = temp;
//        }
        //写法2:
        for (int i = 0,j = arr.length -1; i < j; i++,j--) {
    
    
            int temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        }
        System.out.println(Arrays.toString(arr));
    }
}

Guess you like

Origin blog.csdn.net/qq_44273739/article/details/131911049