我可以在Java中使用.length来找出数组的长度

时间:2012-06-28 01:08:32

标签: java

我有以下内容:

int count = args.length;

看起来很奇怪我想在不使用长度字段的情况下找出数组长度。还有其他办法吗?

这是我已经尝试过的(没有成功):

int count=0; while (args [count] !=null) count ++;
int count=0; while (!(args[count].equals(""))) count ++;}

5 个答案:

答案 0 :(得分:2)

我认为没有必要这样做。但是,最简单的方法是使用enhanced for loop

 int count=0;
 for(int i:array)
 {
   count++;
 }

 System.out.println(count);

答案 1 :(得分:0)

我不确定你为什么要做其他任何事情,但这只是我想出来看看会有什么用。这对我有用:

    int count = 0;
    int[] someArray = new int[5];  
    int temp;
    try
    {
        while(true)
        {
            temp = someArray[count];
            count++;
        }
    }
    catch(Exception ex)
    {
           System.out.println(count); 
    }

答案 2 :(得分:0)

如果索引超出范围,则无法使用[]访问数组。

您可以使用for-each循环

for (String s: args){
    count++;
}

答案 3 :(得分:0)

public class ArrayLength {
    static int number[] = { 1, 5, 8, 5, 6, 2, 4, 5, 1, 8, 9, 6, 4, 7, 4, 7, 5, 1, 3, 55, 74, 47, 98, 282, 584, 258, 548,
            56 };

    public static void main(String[] args) {
        calculatingLength();
    System.out.println(number.length);
    }

    public static void calculatingLength() {
        int i = 0;
        for (int num : number) {

            i++;

        }
        System.out.println("Total Size Of Array :" + i);

    }


}

答案 4 :(得分:-1)

Arrays.asList(yourArray).size();怎么样?

相关问题