Three expansion methods of Java arrays and program implementation

In Java, an array is a continuous storage space in memory. When the array is created, the address is fixed and the space does not change. Therefore, to expand the array, we must create a new array.

When transferring values ​​to array type variables in Java, addresses are used.

The principle of Java array expansion

(1) The size of Java array objects is fixed, and array objects cannot be expanded.

(2) Array expansion can be achieved flexibly by using the array copy method.

(3) System.arraycopy() can copy an array.

(4) Arrays.copyOf() can easily create a copy of an array.

(5) When creating a copy of the array and increasing the length of the array, the expansion of the array can be achieved in a flexible manner.

Array expansion implementation

  • Create a new array and copy the original array to the new array

  • Use the system-defined function system.arraycopy to achieve capacity expansion

  • System-defined function Arrays.copyof function realizes capacity expansion

The program implementation code is as follows

import java.util.Arrays;
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int[] a = {2,5,8};//定义一个长度为3的数组
        expansion1(a);     //创建新数组,for循环内复制
        expansion2(a);     //System.arraycopy进行复制
        expansion3(a);      //系统自带的Arrays.copyOf
    }
    private static int[] expansion3(int[] a) {
        int[] b = new int[a.length*2];
        for (int i = 0; i < a.length; i++) {
            b[i] = a[i];
        }
        return b;
    }
    private static int[] expansion2(int[] a) {
        int[] b = new int[a.length*2];
        System.arraycopy(a,0,b,0,a.length);
        return b;
    }
    private static int[] expansion1(int[] a) {
        return Arrays.copyOf(a,a.length*2);
    }
}

おすすめ

転載: blog.csdn.net/qq_60575429/article/details/129312598