每日学习-Java基础(八)数组5(复制数组)

一、说明

    // 复制数组
	/* ---参数说明
	 * src    源数组
	 * srcPos 源数组起始位置      从0开始 索引
	 * des    目标数组
	 * desPos 目标数组起始位置  从0开始 索引
	 * length 复制长度
	 * ---功能说明
	 * 从src的srcPos开始,复制length个数据,到des的以desPos为开始的位置处
	 */
	//System.arraycopy(src, srcPos, des, desPos, length);
	
	int[] a = new int[]{1,2,3,4,5,6}; // 长度5
	int[] b = new int[3]; // 长度3
	
	// 赋值方式1
	System.out.println("赋值方式1-:");
	for(int i=0; i<b.length; i++){
		b[i] = a[i];
		System.out.print(b[i] + " "); // 1 2 3
	}
	System.out.println();
	
	// 赋值方式2
	System.out.println("赋值方式2-:");
	// 4 5 6  赋值给 1 2 3
	// a中索引为3(第4个数)的数据开始,复制3个数,到b中索引为0(第1个数)开始的位置处
	System.arraycopy(a, 3, b, 0, 3); 
	for(int i=0; i<b.length; i++){
		System.out.print(b[i] + " "); // 4 5 6
	}
	System.out.println();

运行结果:
在这里插入图片描述
二、练习

    // 练习
	// 1-生成 2个 随机长度 5-10 的数组x,y,为x,y赋0-100的随机数值
	// 2-将步骤1中生成的 x,y 数组 复制 到新的数组z中,z的长度为x,y长度之和
	
	// 练习-1
	int xl = (int) (Math.random()*5+5);
	int[] x = new int[xl];
	
	System.out.println("数组x的长度:" + xl);
	for(int i=0; i<xl; i++){
		x[i] = (int) (Math.random()*100);
		System.out.print(x[i] + " ");
	}
	System.out.println();
	
	int yl = (int) (Math.random()*5+5);
	int[] y = new int[yl];
	
	System.out.println("数组y的长度:" + yl);
	for(int j=0; j<yl; j++){
		y[j] = (int) (Math.random()*100);
		System.out.print(y[j] + " ");
	}
	System.out.println();
	
	// 练习-2
	int zl = xl + yl;
	int[] z = new int[zl];
	
	System.out.println("数组z的长度:" + zl);
	System.arraycopy(x, 0, z, 0, xl);
	System.arraycopy(y, 0, z, xl, yl);
	
	for(int k=0; k<zl; k++){
		System.out.print(z[k] + " ");
	}
	System.out.println();

运行结果:
在这里插入图片描述
我的学习源泉:https://how2j.cn/k/array/array-copyarray/284.html?p=114999
Java自学网站:https://how2j.cn?p=114999

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值