package com.xxx;

import java.lang.reflect.Array;
import java.util.Arrays;

/**
 * com.xxx
 * 2022/4/11
 * user
 * function:在Java中调整数组长度(旧数组,新长度)
 */
public class demo003_resizeArray {
    public static void main(String[] args) {
        int[] a = {1,2,3};
        a = (int[])resizeArray(a,5);
        System.out.println(Arrays.toString(a));
    }

    private static Object resizeArray(Object oldArray, int newSize){
        int oldSize = Array.getLength(oldArray);
        Class<?> componentType = oldArray.getClass().getComponentType();
        Object newArray = Array.newInstance(componentType, newSize);
        int min = Math.min(oldSize, newSize);
        if (0<min) {
            System.arraycopy(oldArray, 0, newArray, 0, min);
        }
        return newArray;
    }
}

运行结果

java数组的长度可以是变量 java数组长度可以改变吗_Math