System.arraycopy()和 Arrays.copyOf()的区别联系(源码深度解析copyOf扩容原理)
1.System.arraycopy()方法
public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length):將指定源數組中的數組從指定位置開始復制到目標數組的指定位置。
例子:
package untl; public class MyObject {public static void main(String[] args) {int arr[]={1,2,3,4,5,6,7,8};int brr[]=new int [10];System.arraycopy(arr,1,brr,3,5);for (int a: brr) {System.out.println(a);}} } 運行結果: 0 0 0 2 3 4 5 6 0 0從例子我們可以得出參數的意思:
從src數組的第srcPos位置的元素開始后的length個元素復制到dest數組里以destPos索引為起始位置往后延申
2.Arrays.copyOf()方法
選擇指定的數組,截斷或填充空值(如果需要),使副本具有指定的長度。以達到擴容的目的
//Arrays的copyOf()方法傳回的數組是新的數組對象,改變傳回數組中的元素值,不會影響原來的數組。 //copyOf()的第二個自變量指定要建立的新數組長度,如果新數組的長度超過原數組的長度,則保留數組默認值 public static <T> T[] copyOf(T[] original, int newLength) {return (T[]) copyOf(original, newLength, original.getClass()); }/*** @Description 復制指定的數組, 如有必要用 null 截取或填充,以使副本具有指定的長度* 對于所有在原數組和副本中都有效的索引,這兩個數組相同索引處將包含相同的值* 對于在副本中有效而在原數組無效的所有索引,副本將填充 null,當且僅當指定長度大于原數組的長度時,這些索引存在* 返回的數組屬于 newType 類** @param original 要復制的數組* @param newLength 副本的長度* @param newType 副本的類* * @return T 原數組的副本,截取或用 null 填充以獲得指定的長度* @throws NegativeArraySizeException 如果 newLength 為負* @throws NullPointerException 如果 original 為 null* @throws ArrayStoreException 如果從 original 中復制的元素不屬于存儲在 newType 類數組中的運行時類型*/public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {@SuppressWarnings("unchecked")T[] copy = ((Object)newType == (Object)Object[].class)? (T[]) new Object[newLength]: (T[]) Array.newInstance(newType.getComponentType(), newLength);System.arraycopy(original, 0, copy, 0,Math.min(original.length, newLength));return copy; }例子:
public static void main(String[] args) {int[] a = new int[3];a[0] = 0;a[1] = 1;a[2] = 2;int[] b = Arrays.copyOf(a, 10);System.out.println("b.length " + b.length);for (int i : b) {System.out.print(i + " ");}} 運行結果: b.length10 0 1 2 0 0 0 0 0 0 03.兩者的聯系與區別:
聯系:看兩者源代碼可以發現copyOf()內部調用了System.arraycopy()方法
區別:
1arraycopy()需要目標數組,將原數組拷貝到你自己定義的數組里,而且可以選擇拷貝的起點和長度以及放入新數組中的位置
2.copyOf()是系統自動在內部新建一個數組,并返回該數組。
4.兩者的對比:
1.從兩種拷貝方式的定義來看:
System.arraycopy()使用時必須有原數組和目標數組,Arrays.copyOf()使用時只需要有原數組即可。
2.從兩種拷貝方式的底層實現來看:
System.arraycopy()是用c或c++實現的,Arrays.copyOf()是在方法中重新創建了一個數組,并調用System.arraycopy()進行拷貝。
3.兩種拷貝方式的效率分析:
由于Arrays.copyOf()不但創建了新的數組而且最終還是調用System.arraycopy(),所以System.arraycopy()的效率高于Arrays.copyOf()。
總結
以上是生活随笔為你收集整理的System.arraycopy()和 Arrays.copyOf()的区别联系(源码深度解析copyOf扩容原理)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ArrayList集合的使用和源码详细分
- 下一篇: Java集合 LinkedList的原理