Java中的arraycopy

System.arraycopy拷貝數組,
arraycopy(Object src,int srcPos,Object dest,int destPos,int length)

從指定源數組中複製一個數組,複製從指定的位置開始,到目標數組的指定位置結束。從 src 引用的源數組到
dest 引用的目標數組,數組組件的一個子序列被複製下來。被複制的組件的編號等於 length
參數。源數組中位置在 srcPos 到 srcPos+length-1 之間的組件被分別複製到目標數組中的
destPos 到 destPos+length-1 位置。

 int[] res=new int[]{1,2,3,4,5};
        int[] des=new int[]{6,7,8,9,10};
        System.arraycopy(res,0,res,0,3);
       TextView TV= (TextView) findViewById(R.id.text);
        StringBuffer SB=new StringBuffer();
        for (int i=0;i<res.length;i++){
            SB.append(res[i]);
        }
        TV.setText(SB.toString());
打印結果12345;

如果參數 src 和 dest 引用相同的數組對象,則複製的執行過程就好像首先將
srcPos 到 srcPos+length-1 位置的組件複製到一個帶有
length 組件的臨時數組,然後再將此臨時數組的內容複製到目標數組的 destPos 到
destPos+length-1 位置一樣。

int[] res=new int[]{1,2,3,4,5};
        int[] des=new int[]{6,7,8,9,10};
        System.arraycopy(res,1,res,0,3);
       TextView TV= (TextView) findViewById(R.id.text);
        StringBuffer SB=new StringBuffer();
        for (int i=0;i<res.length;i++){
            SB.append(res[i]);
        }
        TV.setText(SB.toString());

假如這樣的話就是23445.。。。

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        int[] res=new int[]{1,2,3,4,5};
        int[] des=new int[]{6,7,8,9,10};
        System.arraycopy(res,1,des,0,3);
       TextView TV= (TextView) findViewById(R.id.text);
        StringBuffer SB=new StringBuffer();
        for (int i=0;i<des.length;i++){
            SB.append(des[i]);
        }
        TV.setText(SB.toString());
        //System.out.print(des.toString());
    }
}

打印結果是234910.

好明顯的道理就是我們是爲了得到目標數組,原數組只起被複制的功能,我們打印一萬遍源數組還是不變的。但是我們要考慮的是,我們複製的長度再加上目標數組的起始位置不能大於目標數組的長度,

 System.arraycopy(res,1,des,4,3);

我們不能從目標數組第四位加起,還截取3,那麼就.ArrayIndexOutOfBoundsException:數組下標越界了。
所以要慎重。

發佈了53 篇原創文章 · 獲贊 8 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章