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

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

发布了31 篇原创文章 · 获赞 0 · 访问量 335

猜你喜欢

转载自blog.csdn.net/qq_36360463/article/details/104160469
今日推荐