代碼示範
import java.util.Arrays;
public class CopyArray {
public static void main(String[] args) {
// 繼承Object類中的clone()方法
int[] a = {1,2,3,4};
int[] copyA = a.clone();
// System類中的方法
int[] cpA = new int[4];
System.arraycopy(a, 0, cpA, 0, 4);
// 使用數組工具中的方法
int[] cppA = Arrays.copyOf(a, 4);
int[] cppA1 = Arrays.copyOfRange(a, 0, 4);
// 通過for循環來指派數組
int[] cpppA = new int[4];
for (int i = 0; i < a.length; i++) {
cpppA[i] = a[i];
}
a[0] = 12;
a[1] = 12; // 更改原數組對所複制的數組沒有影響
System.out.println(Arrays.toString(copyA)); // [1, 2, 3, 4]
System.out.println(Arrays.toString(cpA)); // [1, 2, 3, 4]
System.out.println(Arrays.toString(cppA)); // [1, 2, 3, 4]
System.out.println(Arrays.toString(cppA1)); // [1, 2, 3, 4]
System.out.println(Arrays.toString(cpppA)); // [1, 2, 3, 4]
}
}
方法分析
- for循環
通過周遊依次指派新的數組即可,但效率不高,寫的也麻煩
- System.arrayCopy(Object src, int srcPos, Object dest, int destPos, int length)
這個方法就靈活很多,不但可以複制數組,還可以任意複制一個數組中任意部分到另一個數組.
還可以合并兩個數組(前提兩個數組中其中一個數組可以容納兩個數組的所有元素.
參數解釋 :
src - 源數組。
srcPos - 源數組中的起始位置。
dest - 目标數組。
destPos - 目标資料中的起始位置。
length - 要複制的數組元素的數量。
- clone()方法
這個方法是從何而來呢?API中又沒有數組的相關介紹.
你可以這樣想,數組是對象吧,那麼所有類的頂層父類都是Object類.
是以clone()方法存在于Object類中.
- Arryas.copyOf(int[] original, int newLength)
參數解釋 :
original - 要複制的數組
newLength - 要傳回的副本的長度
- Arrays.copyOfRange(int[] original, int from, int to)
參數解釋 :
original - 将要從其複制一個範圍的數組
from - 要複制的範圍的初始索引(包括)
to - 要複制的範圍的最後索引(不包括)。(此索引可以位于數組範圍之外)。
- 效率問題
- 深度分析參考