我们如何用Java从另一个数组复制一个数组
让我们首先创建一个字符串数组-
String[] arr = new String[] { "P","Q", "R", "S", "T"};
现在,计算上述数组的长度,并创建一个具有相同长度的新数组-
int len = arr.length; String[] arr2 = new String[len];
让我们从另一个复制一个数组-
System.arraycopy(arr, 0, arr2, 0, arr.length);
示例
public class Demo { public static void main(String[] args) { String[] arr = new String[] { "P","Q", "R", "S", "T"}; System.out.println("Initial array..."); for (int i = 0; i < arr.length; i++) System.out.println(arr[i]); int len = arr.length; String[] arr2 = new String[len]; System.arraycopy(arr, 0, arr2, 0, arr.length); System.out.println("New array...copied"); for (int i = 0; i < arr2.length; i++) System.out.println(arr2[i]); } }
输出结果
Initial array... P Q R S T New array...copied P Q R S T