Java 利用Array.newInstance创建动态数组突破Array本身限制

1,创建一个字符串数组修改其中的索引值并打印

/**
 * Created by Administrator on 2018/1/28.
 */
public class DynamicArrayTest {

    public static final void main(String... args) throws Exception {
        Class clazz = Class.forName("java.lang.String");
        //创建一个长度为10的字符串数组,在Java中数组也可以作为Object对象
        Object array = Array.newInstance(clazz, 10);
        //把字符串数组对象的索引位置为5的元素设置为"hello"
        Array.set(array, 5, "hello");
        //获得字符串数组对象的索引位置为5的元素的值
        String str = (String)Array.get(array, 5);
        //打印
        System.out.println(str);
    }
}

Array.newInstance(clazz, 10)调用链分析:

public static Object newInstance(Class componentType, int length)
            throws NegativeArraySizeException {
        return newArray(componentType, length);
    }
//在Array类中调用了静态nativ方法来实现
 private static native Object newArray(Class componentType, int length)
            throws NegativeArraySizeException;
2、Java中动态修改数组(Array)的大小
/**
 * Created by Administrator on 2018/1/28.
 */
public class DynamicArrayTest {

    private static Object resizeArray (Object oldArray, int newSize) {
        //获取数组oldArray的长度
        int oldSize = Array.getLength(oldArray);
        //获取数组oldArray的元素类型
        Class elementType = oldArray.getClass().getComponentType();
        //实例一个新的数组 类型和oldArray的一样 长度参数传入的newSize
        Object newArray = Array.newInstance(elementType,newSize);
        //得到新数组newArray 和oldArray两个中长度最短的,并把长度返回给preserveLength
        int preserveLength = Math.min(oldSize,newSize);
        //数组内容复制
        if (preserveLength > 0) {
            System.arraycopy (oldArray, 0, newArray, 0, preserveLength);
        }
        return newArray;
    }

    public static final void main(String... args) throws Exception {
        int[] a = {1,2,3};
        a = (int[])resizeArray(a,5);
        a[3] = 4;
        a[4] = 5;
        for (int i=0; i

你可能感兴趣的:(JAVA)