獲取 Java 中陣列的維度


為了獲得 Java 中的陣列維度,我們結合決策制定和迭代語句使用了 getClass()、isArray() 和 getComponentType() 方法。

getClass() 方法返回物件的執行時類。getClass() 方法是 java.lang.Object 類的組成部分。

宣告 - java.lang.Object.getClass() 方法按如下方式宣告 -

public final Class getClass()

isArray() 方法檢查傳遞的引數是否為一個數組。它返回一個布林值,true 或 false

語法 - isArray() 方法具有以下語法

Array.isArray(obj)

getComponentType() 方法返回表示陣列元件型別的 Class。如果該類不是陣列類,則此方法返回 null。

宣告 - java.lang.Class.getComponentType() 方法按如下方式宣告 -

public Class<?> getComponentType()

我們來看一個程式,該程式獲取 Java 中陣列的維度 -

示例

public class Example {
   public static int dimensionOf(Object arr) {
      int dimensionCount = 0;
      Class c = arr.getClass(); // getting the runtime class of an object
      while (c.isArray()) // check whether the object is an array {
         c = c.getComponentType(); // returns the class denoting the component type of the array
         dimensionCount++;
      }
      return dimensionCount;
   }
   public static void main(String args[]) {
      String[][][] array = new String[7][9][8]; // creating a 3 dimensional String array
      System.out.println(dimensionOf(array));
   }
}

更新於:2020 年 6 月 29 日

1K+ 次瀏覽

啟動你的職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.