1、 获得a数组对应的类对象
Class cl = a.getClass();
2、确认是一个数组
if (!cl.isArray()){
return null;
}
3、使用Class类的getComponentType方法确定数组对应的类型
Class componentType = cl.getComponentType();
4、构造新数组
Object newArray = Array.newInstance(componentType,length);
源代码:
public static Object goodCopyOf(Object a,int newLength){
Class cl = a.getClass();
if (!cl.isArray()){
return null;
}
Class componentType = cl.getComponentType();
int length = Array.getLength(a);
Object newArray = Array.newInstance(componentType,length);
System.arraycopy(a,0,newArray,0,Math.min(length,newLength));
return newArray;
}
本文介绍了一种使用Java标准库高效复制数组的方法。通过利用Class类的isArray()方法判断是否为数组,并采用getComponentType()获取数组元素类型,再用Array.newInstance()创建新数组并借助System.arraycopy()完成元素复制。
1万+

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



