得到一个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;
}
本文介绍了一种使用Java实现数组动态扩容的方法。通过获取数组的类型、创建新数组并利用System.arraycopy进行元素复制来完成扩容过程。同时提供了一个具体的示例程序。
15

被折叠的 条评论
为什么被折叠?



