📜  如何确定Java中数组的长度或大小?

📅  最后修改于: 2022-05-13 01:54:52.053000             🧑  作者: Mango

如何确定Java中数组的长度或大小?

数组没有可用的 size() 方法。但是数组中有一个可用的长度字段,可用于查找数组的长度或大小。

array.length:长度是适用于数组的最终变量。借助长度变量,我们可以获得数组的大小。

例子:

int size = arr[].length;

// length can be used 
// for int[], double[], String[] 
// to know the length of the arrays.

下面是如何使用长度变量在Java中获取数组 [] 的长度的说明:

示例 1:

// Java program to illustrate
// how to get the length of the array
  
public class Test {
    public static void main(String[] args)
    {
  
        // Here array is the
        // array name of int type
        int[] array = new int[4];
  
        System.out.println("The size of "
                           + "the array is "
                           + array.length);
    }
}
输出:
The size of the array is 4

示例 2:

// Java program to illustrate
// how to get the length of the array
  
public class Test {
    public static void main(String[] args)
    {
  
        // Here str is the array name
        // of String type.
        String[] str
            = { "GEEKS", "FOR", "GEEKS" };
  
        System.out.println("The size of "
                           + "the array is "
                           + str.length);
    }
}
输出:
The size of the array is 3