Java 陣列的型別有哪些?
Java 中有兩種陣列,它們是 −
單維陣列 − Java 中的單維陣列是一個普通陣列,其中陣列包含的順序元素(型別相同) −
int[] myArray = {10, 20, 30, 40}
示例
public class TestArray { public static void main(String[] args) { double[] myList = {1.9, 2.9, 3.4, 3.5}; // Print all the array elements for (int i = 0; i < myList.length; i++) { System.out.println(myList[i] + " "); } // Summing all elements double total = 0; for (int i = 0; i < myList.length; i++) { total += myList[i]; } System.out.println("Total is " + total); // Finding the largest element double max = myList[0]; for (int i = 1; i < myList.length; i++) { if (myList[i] > max) max = myList[i]; } System.out.println("Max is " + max); } }
輸出
1.9 2.9 3.4 3.5 Total is 11.7 Max is 3.5
多維陣列 − Java 中的多維陣列是陣列的陣列。二維陣列是一維陣列的陣列,三維陣列是二維陣列的陣列。
示例
public class Tester { public static void main(String[] args) { int[][] multidimensionalArray = { {1,2},{2,3}, {3,4} }; for(int i = 0 ; i < 3 ; i++){ //row for(int j = 0 ; j < 2; j++){ System.out.print(multidimensionalArray[i][j] + " "); } System.out.println(); } } }
輸出
1 2 2 3 3 4
廣告