1. 一維數組的聲明和初始化,分成動態和靜態:view plaincopy to clipboardprint? 01.// 動態創建10個整型,默認初始化為0 02.int[] a1 = new int[10]; 03. 04.// 靜態創建4個整型,并初始化為括號中的值 05.int[] a2 = {1, 2, 3, 4}; 06. 07.// 動態創建MyClass數組,需要遍歷創建數組中的每個類實例 08.MyClass[] a3 = new MyClass[3]; 09.for (int i = 0; i < a3.length; ++i) 10. MyClass = new MyClass(); 11. 12.// 靜態創建MyClass數組,用括號中的實例初始化數組 13.MyClass[] a4 = {new MyClass(), new MyClass(), new MyClass}; // 動態創建10個整型,默認初始化為0 int[] a1 = new int[10]; // 靜態創建4個整型,并初始化為括號中的值 int[] a2 = {1, 2, 3, 4}; // 動態創建MyClass數組,需要遍歷創建數組中的每個類實例 MyClass[] a3 = new MyClass[3]; for (int i = 0; i < a3.length; ++i) MyClass = new MyClass(); // 靜態創建MyClass數組,用括號中的實例初始化數組 MyClass[] a4 = {new MyClass(), new MyClass(), new MyClass}; 2. 多維數組可理解為數組的數組,同樣可以有兩種聲明形式:view plaincopy to clipboardprint? 01.public class Main { 02. static void printInt(int[][] ints) { 03. for (int i = 0; i < ints.length; ++i) 04. for (int j = 0; j < ints.length; ++j) 05. System.out.println(ints[j]); 06. } 07. 08. public static void main(String[] args) { 09. // 動態創建二維數組,并遍歷初始化之 10. int[][] ints = new int[2][2]; 11. for (int i = 0; i < ints.length; ++i) 12. for (int j = 0; j < ints.length; ++j) 13. ints[j] = i + j; 14. printInt(ints); 15. 16. // 靜態創建二維數組 17. int[][] ints2 = {{1, 2}, {3, 4}}; 18. printInt(ints2); 19. } 20.} public class Main { static void printInt(int[][] ints) { for (int i = 0; i < ints.length; ++i) for (int j = 0; j < ints.length; ++j) System.out.println(ints[j]); } public static void main(String[] args) { // 動態創建二維數組,并遍歷初始化之 int[][] ints = new int[2][2]; for (int i = 0; i < ints.length; ++i) for (int j = 0; j < ints.length; ++j) ints[j] = i + j; printInt(ints); // 靜態創建二維數組 int[][] ints2 = {{1, 2}, {3, 4}}; printInt(ints2); } } 3. 可變數組的聲明形式:view plaincopy to clipboardprint? 01.public class Main { 02. static void printInt(int[][] ints) { 03. for (int i = 0; i < ints.length; ++i) 04. { 05. for (int j = 0; j < ints.length; ++j) 06. System.out.print(ints[j] + " "); 07. System.out.println(); 08. } 09. } 10. 11. public static void main(String[] args) { 12. // 動態創建二維可變數組,先創建第一維 13. int[][] ints = new int[2][]; 14. // 再確定第二維的元素數 15. for (int i = 0; i < ints.length; ++i) 16. ints = new int[i + 3]; 17. printInt(ints); 18. 19. // 靜態創建二維可變數組 20. int[][] ints2 = {{1, 2}, {3, 4, 5}}; 21. printInt(ints2); 22. } 23.} 24.// 輸出為: 25.0 0 0 26.0 0 0 0 27.1 2 28.3 4 5 |