62,612
社区成员
发帖
与我相关
我的任务
分享
/**
* ClassName:CopyOfTest
* Author:LFM
* Date:2019/6/14 12:35
**/
public class CopyOfTest {
public static void main(String[] args) {
int [] a = {1,2,3,4,5,6};//定义一个整型数组
a = (int[]) goodCopyOf(a,10);
System.out.println(Arrays.toString(a));
}
/**
*@author LFM
*@Description 利用这个方法进行数组的复制会抛出异常
*@date 2019/6/14
*/
public static Object[] badCopyOf(Object[] a,int newLength){
Object[] newArray = new Object[newLength];
System.arraycopy(a,0,newArray,0,Math.min(a.length,newLength));
return newArray;
}
public static Object goodCopyOf(Object a,int newLength){
Class c1 = a.getClass();
if (!c1.isArray()) return null;//首先确定是一个数组
Class componentType = c1.getComponentType();//使用Class类的getComponentType()方法确定数组类型
int length = Array.getLength(a);
Object newArray = Array.newInstance(componentType,newLength);
System.out.println(length);
System.out.println(newLength);
System.arraycopy(a,0,newArray,0,Math.min(length,newLength));
return newArray;
}
}