Java使用System.arraycopy()实现数组之间的复制

System提供了函数arraycopy(),将指定源数组中的数组从指定位置复制到目标数组的指定位置。

1
2
3
4
5
6
7
8
/**
* @param src 源数组
* @param srcPos 拷贝的起始位置
* @param dest 要拷贝进的数组
* @param destPos 拷贝的位置起始下标
* @param length 拷贝的数组长度
*/
public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length);

使用方法如下:

1
2
3
4
5
6
7
8
9
10
11
12
@Test
public void stringTest() {
//源数组
String[] str1 = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
//要拷贝的目标数组
String[] str2 = {"一", "二", "三", "四", null, null, null};

System.arraycopy(str1, 5, str2, 4, 3);
for (String str:str2) {
System.out.print(str);
}
}

如上代码返回的结果为:

script
1
一二三四伍陆柒

作者: 只是学习学习
邮箱: fengzxia1000@163.com
原文地址: https://fengzxia.gitee.io/posts/e8b6833a.html
版权声明: 商业转载请联系作者获得授权,非商业转载请注明出处。