一、將數組元素逐個復制到目標數組中
例1
//源數組 int[] source = {10,30,20,40}; //目標數組 int[] target = new int[source.length]; for (int i = 0;i < source.length;i++){ target[i] = source[i]; }
二、使用System類的arraycopy()方法
public static void arraycopy(Object src,int srcPos,Object dest,int desPos,int length)
例2
package com.demo; public class ArrayCopyDemo{ public static void main(String[] args){ int[] a = {1,2,3,4}; int[] b ={8,7,6,5,4,3,2,1}; int[] c = {10,20}; try{ System.arraycopy(a, 0, b, 0, a.length); // 下面語句發生異常,目標數組c容納不下原數組a的元素 System.arraycopy(a, 0, c, 0, a.length); }catch(ArrayIndexOutOfBoundsException e){ System.out.println(e); } for(int elem: b){ System.out.print(elem+" "); } System.out.println(); for(int elem: c){ System.out.print(elem+" "); } System.out.println("\n"); } }
注意:如果目標數組不足以容納源數組元素,會拋出異常
java.lang.ArrayIndexOutOfBoundsException(數組下標越界異常)
三、使用Arrays類的copyOf()方法和copyOfRange()方法
1、copyOf()方法格式
以整型為例
如果newLength小於源數組的長度,則將源數組的前面若干個元素復制到目標數組。
如果newLength大於源數組的長度,則將源數組的所有元素復制到目標數組。
如:
2.copyOfRange()方法格式
以字符型為例
如:
上述代碼執行后,letter數組的長度變為4,包含'b'、'c'、‘d’、'e'4個元素