JAVA 數(shù)組復制的方法
1、使用for循環(huán)遍歷,效率最低
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表示要復制的數(shù)組;newlength表示要復制的長度,如果newlength>original.length,多出的部分將以數(shù)組默認值的方式給出 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() 復制指定長度的數(shù)組
public static <T> T[] copyOfRange(T[] original,int from,int to) // 左閉右開// T - 數(shù)組中對象的類 // original - 要從中復制范圍的數(shù)組 // from - 要復制的范圍的初始索引(包括) // to - 要復制的范圍的最終索引,不包括。 (該索引可能位于數(shù)組之外) 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 時,此時超出了原數(shù)組的長度,結果為[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 - 源數(shù)組。 // srcPos - 源數(shù)組中的起始位置。 // dest - 目標數(shù)組。 // destPos - 目的地數(shù)據(jù)中的起始位置。 // length - 要復制的數(shù)組元素的數(shù)量。 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入門程序