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

2021年4月12日11:20:13 发表评论 1,253 次浏览

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

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

例子:

int size = arr[].length;

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

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

示例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

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: