Java - 使用 System.arraycopy 连接两个数组
在本教程中,我们将学习如何合并两个表。以下两个示例提供了两种不同的串联方法:一种是用于学习的学术方法,另一种是 System.arraycopy().1) 经典方法:浏览两个数组
public class ConcatArrays {Output
public static void main(String[] args) {
String[] t1 = {1”,2”,3”};
字符串[] t2 = {4”,5”,6”};
字符串[] t12 = 新字符串[t1.length+t2.length];
/*串联*/
for(int i = 0 ; i < t1.length; i++)
t12[i]=t1[i];
for(int i = 0 ; i < t2.length; i++)
//我们继续在 t12 中复制 index
//我们已经停止的 t1
t12[i+t1.length]=t2[i];
for(int i = 0 ; i < t12.length; i++)
System.out.println(t12[i]);
}
}
1
2
3
4
5
6
2) 使用 System.arraycopy()
此方法高效, 您可以使用它将项目从源表复制到目标表。它接受五个参数:
- 源数组(t1 和 t2).
- 要从源数组的哪个位置开始(在我们的例子中为 0).
- 目标数组 (t12).
- 要从目标数组的哪个位置开始。
- 0 for t1.
- t1.lenght for t2.
- 要复制的元素数(不是停止位置).
public class ConcatArrays {输出
public static void main(String[] args) {
char[] t1 = {'a','b','c'};
char[] t2 = {'d','e','f'};
char[] t12 = 新字符[t1.length+t2.length];
//第一个数组的副本
System.arraycopy(t1, 0, t12, 0, t1.length);
//第二个数组的副本 array
System.arraycopy(t2, 0, t12, t1.length, t2.length);
for(int i = 0 ; i < t12.length; i++)
System.out.println(t12[i]);
}
}
aReferences
b
c
d
e
f
Oracle 文档:System
TutorialsPoint: Java.lang.System.arraycopy() 方法