下文笔者将讲述使用反射对数组进行扩容的方法分享,如下所示:
实现思路:
创建新的数组实例,然后对源数组进行复制操作
例:
package com.java265.other;
import java.lang.reflect.Array;
public class TestClass {
public static void main(String[] args) throws Exception {
int[] arr = { 10, 20 };
System.out.println("数组长度:" + arr.length);
// 数组扩容 --在原数组的基础上扩容2倍
Object obj = Array.newInstance(arr.getClass().getComponentType(), arr.length * 2);
System.arraycopy(arr, 0, obj, 2, 2);
System.out.println(Array.getInt(obj, 0));
System.out.println(Array.getInt(obj, 1));
System.out.println(Array.getInt(obj, 2));
System.out.println(Array.getInt(obj, 3));
}
}
----运行以上代码,将输出以下信息----
数组长度:2
0
0
10
20
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


