Java中System.arraycopy()方法问题(这里的0是怎么出现的,有大佬解释以下么?)

廖子默 廖子默 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
源代码如下
/**
* 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;
}

}

其中我调用那个goodCopyOf()方法,使用一个Math.min()方法,按道理应该返回数值小的那个(即原本数组的长度6),为什么最后还是出现新数组长度为10?(话说不清楚,运行结果如下:)

...全文
评论 2
收藏 已收藏
分享
返回顶部
廖子默
Java SE 62,620 成员 307,251 内容