一位數組的初始化(兩種方法)
數組類型數組明[]={值1,值2,值3......值n};
數組類型數組名[]=new 數據類型[常數值] //這個方法會賦予所有的陣列元素同一個預設值,對數值類型來說,預設值也是0
1.陣列的遍歷
除了for循環,比較簡單的是for-each語句;
格式:for(類型 變數名稱:陣列)
public class bianli { public static void main(String[] args) { // TODO Auto-generated method stub int a[]={1,2,3,4,5,6,7}; for( int i:a){ System.out.print(i); } } }
Ps :直接遍歷的方法
Arrays.asList(a)//a是要遍歷的目標數組
import java.util.*; public class asList { public static void main(String[] args) { // TODO Auto-generated method stub String[] A={"I","L","O","V","E","J","A","V","A"}; System.out.println("数组A:"+Arrays.asList(A)); } }
System.arraycopy(a,b,c,d,) /a:來源數組b:從哪個位置開始複製c:目標數組d:偏移量e:要從來源數組中複製到目標數組元素的個數
public class arraycopy { public static void main(String[] args){ String A[]={"H","e","1","1","0"}; String B[]=new String[6]; System.arraycopy(A, 0, B, 1, B.length-1); for(int i=0;i<B.length;i++){ System.out.print(B[i]+" "); } } }
運行之後的結果
3:運行之後的結果3:填入Arrays.Fill(a,b) // a:目標陣列名稱b:要填入的值import java.util.*; public class tianchong { public static void main(String[] args) { // TODO Auto-generated method stub String[] A=new String[3]; Arrays.fill(A, "I love you"); for(int i=0;i<A.length;i++){ System.out.println(A[i]+" "); } } }
import java.util.Arrays; public class xiangdeng { public static void main(String[] args) { // TODO Auto-generated method stub String[] A={"a","b","c"}; String[] B={"A","B","C"}; String[] C={"a","b","c"}; System.out.println("数组A和B相等:"+Arrays.equals(A, B)); System.out.println("数组A和c相等:"+Arrays.equals(A, C)); } }