1.1数组复制的几种常见用法
1.1.1System.arraycopy的用法
int[] src = {1,3,5,7,9,11,13,15,17};
int[] dest = {2,4,6,8,10,12,14,16,18,20};
//从src中的第一个元素起复制三个元素,即1,3,5复盖到dest第2个元素开始的三个元素
System.arraycopy(src, 0, dest, 1, 3);
System.out.println(Arrays.toString(dest));
结果为:[2, 1, 3, 5, 10, 12, 14, 16, 18, 20]
1.1.2Arrays.copyOf的用法
int[] src = {1,3,5,7,9,11,13,15,17};
int[] dest = {2,4,6,8,10,12,14,16,18,20};
//copyOf(是复制src数组从0开始的两个元素到新的数组对象)
int[] copyof=Arrays.copyOf(src, 2);
System.out.println(Arrays.toString(copyof));
结果为:[1, 3]
1.1.3 Arrays.copyOfRange的用法
int[] src = {1,3,5,7,9,11,13,15,17};
int[] dest = {2,4,6,8,10,12,14,16,18,20};
//copyRange(从src数组中从0开始的第二个元素到第五个元素复制到新数组,含头不含尾)
int[] copyofRange=Arrays.copyOfRange(src, 2,6);
System.out.println(Arrays.toString(copyofRange));
结果为:[5, 7, 9, 11]
希望能给您带来帮助!
时间: 2024-10-19 00:20:02