Java數組聲明的三種方式
第一種(聲明並初始化):
數據類型[] 數組名={值,值,...};
例:int[] a = {1,2,3,4,5,6,7,8};
第二種(聲明后賦值):
數據類型[] 數組名 = new 數據類型[數組長度];
數組名[下標1]=值;數組名[下標2]=值;.....
例:String[] a =new String[4];
a[0]="hello";
a[1]="world";
....
第三種():
數據類型[] 數組名=new 數據類型[]{值,值,...};
Java數組拷貝的四種方式
第一種:for循環自己手寫,注意數組越界異常
第二種: System.arraycopy(src, srcPos, dest, destPos, length);
Object src,int srcPos,Object dest,int descPos,int length
源數組,源數組開始拷貝位置,目標數組,目標數組開始拷貝位置,拷貝長度
第三種:java.util.Arrays.Arrays.copyOf(源數組,新數組長度);
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;
}
這個方法有兩個參數,第一個參數是源數組,可以數byte,short,int,long,char,float,double,boolean
第二個參數是新數組長度
該方法先new一個新數組,然后拷貝,返回值是一個數組,需要先聲明一個數組存放返回數組,也可以直接用Arrays.toString(Arrays.copyOf(a,a.length))遍歷
java.util.Arrays.copyOfRange(源數組,開始拷貝位置,結束拷貝位置);
源數組的數據類型和Arrays.copyOf();一樣
public static <T,U> T[] copyOfRange(U[] original, int from, int to, Class<? extends T[]> newType) {
int newLength = to - from;
if (newLength < 0)
throw new IllegalArgumentException(from + " > " + to);
@SuppressWarnings("unchecked")
T[] copy = ((Object)newType == (Object)Object[].class)
? (T[]) new Object[newLength]
: (T[]) Array.newInstance(newType.getComponentType(), newLength);
System.arraycopy(original, from, copy, 0,
Math.min(original.length - from, newLength));
return copy;
}
第四種:clone();
int []h=new int[c.length];
h=(int[])c.clone();
h=c.clone();//h與c同數據類型
Demo:
package syntax;
import java.util.Arrays;
public class ArrayDemo2 {
public static void main(String[] args) {
int[] a={1,2,3,4,5,6,7,8};
int[] b=new int[10];
b[1]=1;
b[2]=2;
int[] c=new int[]{1,2,3,4,5,34,6,7,8,9,12};
System.out.println("數組a="+Arrays.toString(a));
System.out.println("數組b="+Arrays.toString(b));
System.out.println("數組c="+Arrays.toString(c));
System.out.println("\n===System.arraycopy拷貝===");
System.out.println("===把數組c拷貝到長度為a.length的數組d===");
//數組的copy
int[] d=new int[a.length];
System.arraycopy(c, 0, d, 0, a.length);
//從a數組的第0個位置開始復制a.length個數據,復制到數組d第0個位置開始
System.out.println("數組d="+Arrays.toString(d));
System.out.println("\n===Arrays.copyOf拷貝===");
//先new一個新的數組,再將原來數組拷貝到新數組中,原數組引用與其不同
System.out.println("===把數組a拷貝到長度為a.length+1的數組e===");
int[] e=Arrays.copyOf(a, a.length+1);
//從a數組的第0個元素開始復制,復制長度為a.length+1;默認初始化值為0
System.out.println("數組e="+Arrays.toString(e));
System.out.println("\n=========for循環拷貝=========");
System.out.println("===把數組c拷貝到長度為10的數組f===");
//for循環復制
int []f=new int[10];
for(int i=0;i<f.length;i++){
f[i]=c[i];
}
System.out.println("數組f="+Arrays.toString(f));
System.out.println("\n=========clone循環拷貝=========");
System.out.println("===把數組c拷貝到長度為c.length的數組h===");
int []h=new int[c.length];
h=(int[])c.clone();
System.out.println("數組h="+Arrays.toString(h));
}
}
