標籤:大小 under new stp 拷貝 public 改變 each ati
1、定義數組
定義一維數組
int array1[ ];
int [ ] array2,array3;
符號“[]”說明聲明的是一個數組對象。這兩種聲明方式沒有區別,但是第二種可以同時聲明多個數組
// 建立大小為10個整型的數組int[] array = new int[10];// 建立大小為5個整型的數組並初始化int[] array = {1, 2, 3, 4, 5};
2、length執行個體變數
int[] arr = new int[10];
arr.length 表示數組長度
3、一維數組複製
// 從 src 數組 srcPos 位置開始拷貝 length 長度到 dest 數組 destPos 開始的位置
// 參數1:原數組
// 參數2:複製原數組的起始位置
// 參數3:目標數組
// 參數4:目標數組存放的起始位置
// 參數5:複製的長度
System.arraycopy(src, srcPos, dest, destPos, length);
int[] arr1 = new int[5];int[] arr2 = new int[5];// 該語句會把 arr1 也指向 arr2 數組,改變 arr2 數組的值,arr1 數組的值也會改變//arr1 = arr2;// 該語句會把 arr2 數組中的值複製到 arr1 數組中,改變 arr2 中的值,不會影響 arr1 數組//System.arraycopy(arr2, 0, arr1, 0, arr2.length);
4、二維數組
int[][] two = new int[5][6];
two.length表示數組的行數,two[i].length表示數組的列數。
5、不規則數組
int[][] two = new int[4][]; // 數組有4行
two[0] = new int[1]; // 第1行有1列
two[0] = new int[2]; // 第1行有2列
two[0] = new int[3]; // 第1行有3列
two[0] = new int[3]; // 第1行有4列
6、for-each迴圈:用來遍曆數組
// for-each 訪問一維數組public class Array { public static void main(String[] args) { int sum = 0; int[] arr = {1, 2, 3, 4, 5}; for (int i : arr) { sum += i; } System.out.println(sum); }}
結果:15
// for-each 訪問二維數組public class Array { public static void main(String[] args) { int sum = 0; int[][] arr = {{1, 2},{3, 4}}; for (int i[] : arr) { for (int j : i) { sum += j; } } System.out.println(sum); }}
結果:10
Java學習:數組