问题

我来自php背景,在php中,有一个array_size()函数,可以告诉你数组中有多少元素被使用。

aString[]array有类似的方法吗?谢谢。


#1 热门回答(237 赞)

是的,.length(属性,不是方法):

String[] array = new String[10];
int size = array.length;

#2 热门回答(42 赞)

array.length

它实际上是数组的最终成员,而不是方法。


#3 热门回答(16 赞)

此外,注意如果你有一个多维数组可能很有用,你可以通过在你要查询的数组上附加'[0]'来获得相应的维度,直到你到达适当的轴/元组/维度。

使用以下代码可能更好地解释了这一点:

public class Test {
    public static void main(String[] args){
        String[][] moo = new String[5][12];

        System.out.println(moo.length); //Prints the size of the First Dimension in the array
        System.out.println(moo[0].length);//Prints the size of the Second Dimension in the array
    }

}

产生输出:

5
12

原文链接