我可以在不使用 Java 中的 .length 的情况下找出数组的长度吗

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11236848/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 04:20:24  来源:igfitidea点击:

Can I find out the length of an array without using .length in Java

java

提问by Sleiman Jneidi

I have the following:

我有以下几点:

int count = args.length;

Strange as it might seem I want to find out the array length without using the length field. Is there any other way?

奇怪的是,我想在不使用长度字段的情况下找出数组长度。有没有其他办法?

Here's what I already (without success) tried:

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

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

采纳答案by Jeshurun

How about Arrays.asList(yourArray).size();?

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

回答by Sleiman Jneidi

I don't think that there is any need to do this. However, the easiest way to do this ,is to use the enhanced for loop

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

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

 System.out.println(count);

回答by Dan Teesdale

I'm not sure why you would want to do anything else, but this is just something I came up with to see what would work. This works for me:

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

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

回答by Rohit Tripathi

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);

    }


}

回答by Greg Wang

You cannot use [] to access an array if the index is out of bound.

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

You can use for-each loop

您可以使用 for-each 循环

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