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

更新于: 2019 年 7 月 30 日

16K+ 浏览

职业生涯加速启动

完成课程获得认证

开始
广告
© . All rights reserved.