利用反射扩大数组

    xiaoxiao2025-02-09  18

    得到一个Class cla,若其为数组,便可用cla.getComponentType()来得到数组的类型。

    Array.newInstance(类型,长度);可以创建某种类型的数组。

    System.arraycopy(被复制数组,起点,复制到的数组,起点,长度);用来复制数组。

    public static void main(String[]args) { Integer[] in=new Integer[3]; in[0]=0; in[1]=1; in[2]=2; Integer []inte=(Integer[])arrGrow(in); System.out.print(Array.getLength(inte)); } public static Object arrGrow(Object ob) { Class cla=ob.getClass(); Class com=cla.getComponentType(); Object newArr= Array.newInstance(com, (int)(Array.getLength(ob)*1.1+10)); System.arraycopy(ob, 0, newArr, 0, Array.getLength(ob)); return newArr; }

    转载请注明原文地址: https://ju.6miu.com/read-1296270.html
    最新回复(0)