System.arraycopy()和 Arrays.copyOf()的区别联系(源码深度解析copyOf扩容原理)
1.System.arraycopy()方法
public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length):將指定源數(shù)組中的數(shù)組從指定位置開始復(fù)制到目標(biāo)數(shù)組的指定位置。
例子:
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);}} } 運(yùn)行結(jié)果: 0 0 0 2 3 4 5 6 0 0從例子我們可以得出參數(shù)的意思:
從src數(shù)組的第srcPos位置的元素開始后的length個(gè)元素復(fù)制到dest數(shù)組里以destPos索引為起始位置往后延申
2.Arrays.copyOf()方法
選擇指定的數(shù)組,截?cái)嗷蛱畛淇罩?#xff08;如果需要),使副本具有指定的長度。以達(dá)到擴(kuò)容的目的
//Arrays的copyOf()方法傳回的數(shù)組是新的數(shù)組對象,改變傳回?cái)?shù)組中的元素值,不會影響原來的數(shù)組。 //copyOf()的第二個(gè)自變量指定要建立的新數(shù)組長度,如果新數(shù)組的長度超過原數(shù)組的長度,則保留數(shù)組默認(rèn)值 public static <T> T[] copyOf(T[] original, int newLength) {return (T[]) copyOf(original, newLength, original.getClass()); }/*** @Description 復(fù)制指定的數(shù)組, 如有必要用 null 截取或填充,以使副本具有指定的長度* 對于所有在原數(shù)組和副本中都有效的索引,這兩個(gè)數(shù)組相同索引處將包含相同的值* 對于在副本中有效而在原數(shù)組無效的所有索引,副本將填充 null,當(dāng)且僅當(dāng)指定長度大于原數(shù)組的長度時(shí),這些索引存在* 返回的數(shù)組屬于 newType 類** @param original 要復(fù)制的數(shù)組* @param newLength 副本的長度* @param newType 副本的類* * @return T 原數(shù)組的副本,截取或用 null 填充以獲得指定的長度* @throws NegativeArraySizeException 如果 newLength 為負(fù)* @throws NullPointerException 如果 original 為 null* @throws ArrayStoreException 如果從 original 中復(fù)制的元素不屬于存儲在 newType 類數(shù)組中的運(yùn)行時(shí)類型*/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 + " ");}} 運(yùn)行結(jié)果: b.length10 0 1 2 0 0 0 0 0 0 03.兩者的聯(lián)系與區(qū)別:
聯(lián)系:看兩者源代碼可以發(fā)現(xiàn)copyOf()內(nèi)部調(diào)用了System.arraycopy()方法
區(qū)別:
1arraycopy()需要目標(biāo)數(shù)組,將原數(shù)組拷貝到你自己定義的數(shù)組里,而且可以選擇拷貝的起點(diǎn)和長度以及放入新數(shù)組中的位置
2.copyOf()是系統(tǒng)自動在內(nèi)部新建一個(gè)數(shù)組,并返回該數(shù)組。
4.兩者的對比:
1.從兩種拷貝方式的定義來看:
System.arraycopy()使用時(shí)必須有原數(shù)組和目標(biāo)數(shù)組,Arrays.copyOf()使用時(shí)只需要有原數(shù)組即可。
2.從兩種拷貝方式的底層實(shí)現(xiàn)來看:
System.arraycopy()是用c或c++實(shí)現(xiàn)的,Arrays.copyOf()是在方法中重新創(chuàng)建了一個(gè)數(shù)組,并調(diào)用System.arraycopy()進(jìn)行拷貝。
3.兩種拷貝方式的效率分析:
由于Arrays.copyOf()不但創(chuàng)建了新的數(shù)組而且最終還是調(diào)用System.arraycopy(),所以System.arraycopy()的效率高于Arrays.copyOf()。
總結(jié)
以上是生活随笔為你收集整理的System.arraycopy()和 Arrays.copyOf()的区别联系(源码深度解析copyOf扩容原理)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ArrayList集合的使用和源码详细分
- 下一篇: 如何优雅而又不失内涵的在centos7下