定义一个长度为5的数组arr为{'a','b','c','d','e'}的数据值,复制到另外一个数组brr
1、可以通过对象点clone的方式生成一个新的char[]
2、通过for循环复制到新的数组当中
遍历每个元素复制到新数组
char[] arr = {'a','b','c','d','e'};
// 方法1:数组方法clone
char[] brr1 = arr.clone();
// 方法2:遍历,逐个赋值
char[] brr2 = new char[arr.length];
for(int i = 0; i < brr2.length; i++){
brr2[i] = arr[i];
}
// 方法3:Arrays静态方法copyOf(该方法最终调用的方法4里的方法)
char[] brr3 = Arrays.copyOf(arr, arr.length);
// 方法4:System静态方法arraycopy
char[] brr4 = new char[arr.length];
System.arraycopy(arr, 0, brr4, 0, brr4.length);
package csdn20220609;
public class ArrayCopyToOtherArray {
public static void main(String[] args) {
char[] arr = {'a','b','c','d','e'};
char[] other = new char[8];
char[] total = new char[arr.length + other.length];
other[0] = 'f';
other[1] = 'g';
for (int i = 0;i < arr.length;i++) {
total[i] = arr[i];
}
for (int i = 0;i < other.length;i++) {
total[arr.length - 1 + i] = other[i];
}
System.out.println(total);
}
}