Java System.arraycopy 和 Arrays.copyOf 的區(qū)別

System.arraycopy

  • 只有數(shù)組為一維數(shù)組且元素為基本類型、String 類型的時(shí)候是深拷貝县恕,其它情況下都屬于淺拷貝,比如元素是引用類型、二維數(shù)組的情況
  • 調(diào)用的是 native 方法肛搬,性能好
  • 需要傳入 dest
  • 可以指定起始位置和拷貝的長度,比較靈活

    /**
     * Copies an array from the specified source array, beginning at the
     * specified position, to the specified position of the destination array.
     * A subsequence of array components are copied from the source
     * array referenced by <code>src</code> to the destination array
     * referenced by <code>dest</code>. The number of components copied is
     * equal to the <code>length</code> argument. The components at
     * positions <code>srcPos</code> through
     * <code>srcPos+length-1</code> in the source array are copied into
     * positions <code>destPos</code> through
     * <code>destPos+length-1</code>, respectively, of the destination
     * array.
     * <p>
     * If the <code>src</code> and <code>dest</code> arguments refer to the
     * same array object, then the copying is performed as if the
     * components at positions <code>srcPos</code> through
     * <code>srcPos+length-1</code> were first copied to a temporary
     * array with <code>length</code> components and then the contents of
     * the temporary array were copied into positions
     * <code>destPos</code> through <code>destPos+length-1</code> of the
     * destination array.
     * <p>
     * If <code>dest</code> is <code>null</code>, then a
     * <code>NullPointerException</code> is thrown.
     * <p>
     * If <code>src</code> is <code>null</code>, then a
     * <code>NullPointerException</code> is thrown and the destination
     * array is not modified.
     * <p>
     * Otherwise, if any of the following is true, an
     * <code>ArrayStoreException</code> is thrown and the destination is
     * not modified:
     * <ul>
     * <li>The <code>src</code> argument refers to an object that is not an
     *     array.
     * <li>The <code>dest</code> argument refers to an object that is not an
     *     array.
     * <li>The <code>src</code> argument and <code>dest</code> argument refer
     *     to arrays whose component types are different primitive types.
     * <li>The <code>src</code> argument refers to an array with a primitive
     *    component type and the <code>dest</code> argument refers to an array
     *     with a reference component type.
     * <li>The <code>src</code> argument refers to an array with a reference
     *    component type and the <code>dest</code> argument refers to an array
     *     with a primitive component type.
     * </ul>
     * <p>
     * Otherwise, if any of the following is true, an
     * <code>IndexOutOfBoundsException</code> is
     * thrown and the destination is not modified:
     * <ul>
     * <li>The <code>srcPos</code> argument is negative.
     * <li>The <code>destPos</code> argument is negative.
     * <li>The <code>length</code> argument is negative.
     * <li><code>srcPos+length</code> is greater than
     *     <code>src.length</code>, the length of the source array.
     * <li><code>destPos+length</code> is greater than
     *     <code>dest.length</code>, the length of the destination array.
     * </ul>
     * <p>
     * Otherwise, if any actual component of the source array from
     * position <code>srcPos</code> through
     * <code>srcPos+length-1</code> cannot be converted to the component
     * type of the destination array by assignment conversion, an
     * <code>ArrayStoreException</code> is thrown. In this case, let
     * <b><i>k</i></b> be the smallest nonnegative integer less than
     * length such that <code>src[srcPos+</code><i>k</i><code>]</code>
     * cannot be converted to the component type of the destination
     * array; when the exception is thrown, source array components from
     * positions <code>srcPos</code> through
     * <code>srcPos+</code><i>k</i><code>-1</code>
     * will already have been copied to destination array positions
     * <code>destPos</code> through
     * <code>destPos+</code><i>k</I><code>-1</code> and no other
     * positions of the destination array will have been modified.
     * (Because of the restrictions already itemized, this
     * paragraph effectively applies only to the situation where both
     * arrays have component types that are reference types.)
     *
     * @param      src      the source array.
     * @param      srcPos   starting position in the source array.
     * @param      dest     the destination array.
     * @param      destPos  starting position in the destination data.
     * @param      length   the number of array elements to be copied.
     * @exception  IndexOutOfBoundsException  if copying would cause
     *               access of data outside array bounds.
     * @exception  ArrayStoreException  if an element in the <code>src</code>
     *               array could not be stored into the <code>dest</code> array
     *               because of a type mismatch.
     * @exception  NullPointerException if either <code>src</code> or
     *               <code>dest</code> is <code>null</code>.
     */
    //src 源數(shù)組
    //srcPos 源數(shù)組起始位置
    //dest 目標(biāo)數(shù)組
    //destPos 目標(biāo)數(shù)組起始位置
    //length 要拷貝的長度(要拷貝的元素?cái)?shù)量)
    public static native void arraycopy(Object src,  int  srcPos,
                                        Object dest, int destPos,
                                        int length);

測試

   String[] array = {"a", "b", "c", "b", "d"};
        System.out.println("array.length:" + array.length);
        String[] arrayCopy=new String[10];
        System.out.println("arrayCopy.length:" + arrayCopy.length);
        System.arraycopy(array,1,arrayCopy,1,4);
        System.out.println(Arrays.toString(array));
        System.out.println(Arrays.toString(arrayCopy));
        array[2] = "cc";
        System.out.println(Arrays.toString(array));
        System.out.println(Arrays.toString(arrayCopy));
//-------------------------- 結(jié)果 ---------------------
array.length:5
arrayCopy.length:10
[a, b, c, b, d]
[null, b, c, b, d, null, null, null, null, null]
[a, b, cc, b, d]
[null, b, c, b, d, null, null, null, null, null]

Arrays.copyOf

  • 調(diào)用了 System.arraycopy 方法
  • 適合目標(biāo)數(shù)組不明確的情況下使用毕贼,自動創(chuàng)建新的數(shù)組
    /**
     * Copies the specified array, truncating or padding with nulls (if necessary)
     * so the copy has the specified length.  For all indices that are
     * valid in both the original array and the copy, the two arrays will
     * contain identical values.  For any indices that are valid in the
     * copy but not the original, the copy will contain <tt>null</tt>.
     * Such indices will exist if and only if the specified length
     * is greater than that of the original array.
     * The resulting array is of exactly the same class as the original array.
     *
     * @param <T> the class of the objects in the array
     * @param original the array to be copied
     * @param newLength the length of the copy to be returned
     * @return a copy of the original array, truncated or padded with nulls
     *     to obtain the specified length
     * @throws NegativeArraySizeException if <tt>newLength</tt> is negative
     * @throws NullPointerException if <tt>original</tt> is null
     * @since 1.6
     */
    @SuppressWarnings("unchecked")
    public static <T> T[] copyOf(T[] original, int newLength) {
        return (T[]) copyOf(original, newLength, original.getClass());
    }
    /**
     * Copies the specified array, truncating or padding with nulls (if necessary)
     * so the copy has the specified length.  For all indices that are
     * valid in both the original array and the copy, the two arrays will
     * contain identical values.  For any indices that are valid in the
     * copy but not the original, the copy will contain <tt>null</tt>.
     * Such indices will exist if and only if the specified length
     * is greater than that of the original array.
     * The resulting array is of the class <tt>newType</tt>.
     *
     * @param <U> the class of the objects in the original array
     * @param <T> the class of the objects in the returned array
     * @param original the array to be copied
     * @param newLength the length of the copy to be returned
     * @param newType the class of the copy to be returned
     * @return a copy of the original array, truncated or padded with nulls
     *     to obtain the specified length
     * @throws NegativeArraySizeException if <tt>newLength</tt> is negative
     * @throws NullPointerException if <tt>original</tt> is null
     * @throws ArrayStoreException if an element copied from
     *     <tt>original</tt> is not of a runtime type that can be stored in
     *     an array of class <tt>newType</tt>
     * @since 1.6
     */
    public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
        @SuppressWarnings("unchecked")
        //創(chuàng)建一個(gè)新的長度為 newLength 的數(shù)組實(shí)例 
        T[] copy = ((Object)newType == (Object)Object[].class)
            ? (T[]) new Object[newLength]
            : (T[]) Array.newInstance(newType.getComponentType(), newLength);
        //進(jìn)行拷貝温赔,如果長度不足,意味著后面的保留默認(rèn)值鬼癣,此時(shí)是 null
        //Math.min 存在一定量的開銷
        System.arraycopy(original, 0, copy, 0,
                         Math.min(original.length, newLength));
        return copy;
    }

測試

  String[] array = {"a", "b", "c", "b", "d"};
        System.out.println("array.length:" + array.length);
        String[] arrayCopyed = Arrays.copyOf(array, 10);
        System.out.println("arrayCopyed.length:" + arrayCopyed.length);
        System.out.println(Arrays.toString(array));
        System.out.println(Arrays.toString(arrayCopyed));
        array[2] = "cc";
        System.out.println(Arrays.toString(array));
        System.out.println(Arrays.toString(arrayCopyed));
//-------------------------- 結(jié)果 ---------------------
array.length:5
arrayCopyed.length:10
[a, b, c, b, d]
[a, b, c, b, d, null, null, null, null, null]
[a, b, cc, b, d]
[a, b, c, b, d, null, null, null, null, null]
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末陶贼,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子待秃,更是在濱河造成了極大的恐慌拜秧,老刑警劉巖,帶你破解...
    沈念sama閱讀 206,311評論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件章郁,死亡現(xiàn)場離奇詭異枉氮,居然都是意外死亡志衍,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,339評論 2 382
  • 文/潘曉璐 我一進(jìn)店門聊替,熙熙樓的掌柜王于貴愁眉苦臉地迎上來楼肪,“玉大人,你說我怎么就攤上這事惹悄〈航校” “怎么了?”我有些...
    開封第一講書人閱讀 152,671評論 0 342
  • 文/不壞的土叔 我叫張陵泣港,是天一觀的道長暂殖。 經(jīng)常有香客問我,道長当纱,這世上最難降的妖魔是什么呛每? 我笑而不...
    開封第一講書人閱讀 55,252評論 1 279
  • 正文 為了忘掉前任,我火速辦了婚禮坡氯,結(jié)果婚禮上晨横,老公的妹妹穿的比我還像新娘。我一直安慰自己廉沮,他們只是感情好颓遏,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,253評論 5 371
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著滞时,像睡著了一般叁幢。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上坪稽,一...
    開封第一講書人閱讀 49,031評論 1 285
  • 那天曼玩,我揣著相機(jī)與錄音,去河邊找鬼窒百。 笑死黍判,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的篙梢。 我是一名探鬼主播顷帖,決...
    沈念sama閱讀 38,340評論 3 399
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼渤滞!你這毒婦竟也來了贬墩?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 36,973評論 0 259
  • 序言:老撾萬榮一對情侶失蹤妄呕,失蹤者是張志新(化名)和其女友劉穎陶舞,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體绪励,經(jīng)...
    沈念sama閱讀 43,466評論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡肿孵,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 35,937評論 2 323
  • 正文 我和宋清朗相戀三年唠粥,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片停做。...
    茶點(diǎn)故事閱讀 38,039評論 1 333
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡晤愧,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出雅宾,到底是詐尸還是另有隱情养涮,我是刑警寧澤葵硕,帶...
    沈念sama閱讀 33,701評論 4 323
  • 正文 年R本政府宣布眉抬,位于F島的核電站,受9級特大地震影響懈凹,放射性物質(zhì)發(fā)生泄漏蜀变。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,254評論 3 307
  • 文/蒙蒙 一介评、第九天 我趴在偏房一處隱蔽的房頂上張望库北。 院中可真熱鬧,春花似錦们陆、人聲如沸寒瓦。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,259評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽杂腰。三九已至,卻和暖如春椅文,著一層夾襖步出監(jiān)牢的瞬間喂很,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,485評論 1 262
  • 我被黑心中介騙來泰國打工皆刺, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留少辣,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 45,497評論 2 354
  • 正文 我出身青樓羡蛾,卻偏偏與公主長得像漓帅,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個(gè)殘疾皇子痴怨,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,786評論 2 345

推薦閱讀更多精彩內(nèi)容