编程小技巧 将一个数组的一截复制到另一个数组的一截中

Method one:

使用System.arraycopy(src, srcPos, dest, destPos, length)

参数:
src:the source array(要拷贝的源数组)
srcPos:starting position in the source array.(拷贝数据的起始索引,包括此索引拷贝)
dest:the destination array.(目标数组)
destPos:starting position in the destination data.(目标数组的起始位置)
length:the number of array elements to be copied.(拷贝长度)

异常:
IndexOutOfBoundsException:if copying would cause access of data outside array bounds
ArrayStoreException:if an element in the src array could not be stored into the dest array because of a type mismatch.
NullPointerException:if either src or dest is null.

Example one:

public class test {
	public static void main(String[] args) {
		int a[]={0,1,2,3,4,5,6,7,8};
		int b[]=new int[10];
		
		//注意不要索引越界,以及长度过长
		System.arraycopy(a, 2, b, 3, 4);
		
		for(int i=0;i<b.length;i++){
			System.out.println(b[i]);
		}
	}
}

Example one output:

0
0
0
2
3
4
5
0
0
0

## Method two:
使用Arrays.copyOfRange(int[] original, int from, int to)

参数:
original:源数组
from和to:需要复制的索引启止位置,左开右闭
//Arrays.copyOfRange源码,我们发现还是使用System.arraycopy()实现的
public static int[] copyOfRange(int[] original, int from, int to) {
        int newLength = to - from;
        if (newLength < 0)
            throw new IllegalArgumentException(from + " > " + to);
        int[] copy = new int[newLength];
        System.arraycopy(original, from, copy, 0,
                         Math.min(original.length - from, newLength));
        return copy;
    }

Example two:

public class test {
	public static void main(String[] args) {
		int a[]={0,1,2,3,4,5,6,7,8};
		int b[];
		
		b=Arrays.copyOfRange(a, 2, 5);
		
		for(int i=0;i<b.length;i++){
			System.out.println(b[i]);
		}
	}
}

Example two output:

2
3
4

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值