![]() 1. 一維數(shù)組的聲明和初始化,分成動態(tài)和靜態(tài):view plaincopy to clipboardprint? 01.// 動態(tài)創(chuàng)建10個整型,默認初始化為0 02.int[] a1 = new int[10]; 03. 04.// 靜態(tài)創(chuàng)建4個整型,并初始化為括號中的值 05.int[] a2 = {1, 2, 3, 4}; 06. 07.// 動態(tài)創(chuàng)建MyClass數(shù)組,需要遍歷創(chuàng)建數(shù)組中的每個類實例 08.MyClass[] a3 = new MyClass[3]; 09.for (int i = 0; i < a3.length; ++i) 10. MyClass = new MyClass(); 11. 12.// 靜態(tài)創(chuàng)建MyClass數(shù)組,用括號中的實例初始化數(shù)組 13.MyClass[] a4 = {new MyClass(), new MyClass(), new MyClass}; // 動態(tài)創(chuàng)建10個整型,默認初始化為0 int[] a1 = new int[10]; // 靜態(tài)創(chuàng)建4個整型,并初始化為括號中的值 int[] a2 = {1, 2, 3, 4}; // 動態(tài)創(chuàng)建MyClass數(shù)組,需要遍歷創(chuàng)建數(shù)組中的每個類實例 MyClass[] a3 = new MyClass[3]; for (int i = 0; i < a3.length; ++i) MyClass = new MyClass(); // 靜態(tài)創(chuàng)建MyClass數(shù)組,用括號中的實例初始化數(shù)組 MyClass[] a4 = {new MyClass(), new MyClass(), new MyClass}; 2. 多維數(shù)組可理解為數(shù)組的數(shù)組,同樣可以有兩種聲明形式: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. // 動態(tài)創(chuàng)建二維數(shù)組,并遍歷初始化之 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. // 靜態(tài)創(chuàng)建二維數(shù)組 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) { // 動態(tài)創(chuàng)建二維數(shù)組,并遍歷初始化之 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); // 靜態(tài)創(chuàng)建二維數(shù)組 int[][] ints2 = {{1, 2}, {3, 4}}; printInt(ints2); } } 3. 可變數(shù)組的聲明形式: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. // 動態(tài)創(chuàng)建二維可變數(shù)組,先創(chuàng)建第一維 13. int[][] ints = new int[2][]; 14. // 再確定第二維的元素數(shù) 15. for (int i = 0; i < ints.length; ++i) 16. ints = new int[i + 3]; 17. printInt(ints); 18. 19. // 靜態(tài)創(chuàng)建二維可變數(shù)組 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 |