[Java基礎] System.arraycopy使用

來源:互聯網
上載者:User

標籤:

轉載自: http://blog.csdn.net/java2000_net/article/details/4059465

System提供了一個native 靜態方法arraycopy(),我們可以使用它來實現數組之間的複製。其函數原型是: public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length) src:源數組; srcPos:源數組要複製的起始位置; dest:目的數組; destPos:目的數組放置的起始位置; length:複製的長度。 注意:src and dest都必須是同類型或者可以進行轉換類型的數組. 有趣的是這個函數可以實現自己到自己複製.

import java.util.Arrays;/** * 老紫竹JAVA提高教程 - System.arraycopy方法的使用。<br> * <br> * 從指定源數組中複製一個數組,複製從指定的位置開始,<br> * 到目標數組的指定位置結束 * * @author 老紫竹的家(java2000.net,laozizhu.com) * */public class LessionSystemArraycopy {  public static void main(String[] args) {    // 此方位為native方法。    // public static native void arraycopy(    // Object src, int srcPos, Object dest,    // int destPos, int length);    // 初始化    int[] ids = { 1, 2, 3, 4, 5 };    System.out.println(Arrays.toString(ids)); // [1, 2, 3, 4, 5]    // 測試自我複製    // 把從索引0開始的2個數字複製到索引為3的位置上    System.arraycopy(ids, 0, ids, 3, 2);    System.out.println(Arrays.toString(ids)); // [1, 2, 3, 1, 2]    // 測試複製到別的數組上    // 將資料的索引1開始的3個資料複製到目標的索引為0的位置上    int[] ids2 = new int[6];    System.arraycopy(ids, 1, ids2, 0, 3);    System.out.println(Arrays.toString(ids2)); // [2, 3, 1, 0, 0, 0]    // 此功能要求    // 源的起始位置+長度不能超過末尾    // 目標起始位置+長度不能超過末尾    // 且所有的參數不能為負數    try {      System.arraycopy(ids, 0, ids2, 0, ids.length + 1);    } catch (IndexOutOfBoundsException ex) {      // 發生越界異常,資料不會改變      System.out.println("拷貝發生異常:資料越界。");    }    System.out.println(Arrays.toString(ids2)); // [2, 3, 1, 0, 0, 0]    // 如果是類型轉換問題    Object[] o1 = { 1, 2, 3, 4.5, 6.7 };    Integer[] o2 = new Integer[5];    System.out.println(Arrays.toString(o2)); // [null, null, null, null, null]    try {      System.arraycopy(o1, 0, o2, 0, o1.length);    } catch (ArrayStoreException ex) {      // 發生儲存轉換,部分成功的資料會被複製過去      System.out.println("拷貝發生異常:資料轉換錯誤,無法儲存。");    }    // 從結果看,前面3個可以複製的資料已經被儲存了。剩下的則沒有    System.out.println(Arrays.toString(o2)); // [1, 2, 3, null, null]  }}

 

[Java基礎] System.arraycopy使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.