JAVA 數組復制的方法
1、使用for循環遍歷,效率最低
int [] arr = {1,2,3,4,5,6,7,8}; int [] arr1 = new int [arr.length]; for (int i = 0; i <arr.length ; i++) { arr1[i]=arr[i]; } System.out.println(Arrays.toString(arr1)); //結果[1, 2, 3, 4, 5, 6, 7, 8]
(視頻教程推薦:java視頻)
2、使用Arrays中提供的方法
2.1copyof() 效率次于第三種
// orinigal表示要復制的數組;newlength表示要復制的長度,如果newlength>original.length,多出的部分將以數組默認值的方式給出 public static int[] copyOf(int[] original,int newLength) int [] arr = {1,2,3,4,5,6,7,8}; int [] arr2 = Arrays.copyOf(arr,3); System.out.println(Arrays.toString(arr2));// 輸出 [1, 2, 3]
2.2copyOfRange() 復制指定長度的數組
public static <T> T[] copyOfRange(T[] original,int from,int to) // 左閉右開// T - 數組中對象的類 // original - 要從中復制范圍的數組 // from - 要復制的范圍的初始索引(包括) // to - 要復制的范圍的最終索引,不包括。 (該索引可能位于數組之外) int [] arr = {2,5,4,6,8,7}; int [] arr2 = Arrays.copyOfRange(arr,1,7); System.out.println(Arrays.toString(arr2));// 輸出[2, 3, 4, 5, 6, 7] // 當 to 的值為 9 時,此時超出了原數組的長度,結果為[2, 3, 4, 5, 6, 7, 8, 0]
3、System.arraycopy() 效率最高
public static void arraycopy(Object src,int srcPos,Object dest,int destPos,int length) // src - 源數組。 // srcPos - 源數組中的起始位置。 // dest - 目標數組。 // destPos - 目的地數據中的起始位置。 // length - 要復制的數組元素的數量。 int [] arr = {1,2,3,4,5,6,7,8}; int [] arr3=new int [arr.length]; System.arraycopy(arr,1,arr3,2,5); System.out.println(Arrays.toString(arr3)); // 結果[0, 0, 2, 3, 4, 5, 6, 0]
推薦教程:java入門程序