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


在Java中,确定数组长度或大小的一种便捷方法是使用它的`length`属性。它计算数组中存储的元素数量并返回计数。查找数组的长度是一种常见但至关重要的操作,因为它用于查找数组的元素数量、向其中追加新元素以及检索存储的项。本文旨在解释获取数组长度或大小的各种方法。

确定数组长度或大小的Java程序

下面的例子将帮助我们理解如何找到数组的大小。

示例1

以下示例说明了将`length`属性与整数类型数组一起使用的用法。

import java.util.*;
public class Example1 {
   public static void main(String[] args) {
      int[] aray = new int[5]; // declaring array of size 5
      // initializing the array
      aray[0] = 11;
      aray[1] = 21;
      aray[2] = 13;
      aray[3] = 23;
      aray[4] = 30;
      // printing the elements of array
	  System.out.println("Elements of the given array: ");
	  for(int elm : aray) {
	     System.out.print(elm + " "); 
	  }
	  System.out.println();
	  // printing the length of array
      System.out.println("Length of the given array: " + aray.length); 
   }
}   

输出

Elements of the given array: 
11 21 13 23 30 
Length of the given array: 5

在上面的代码中,我们声明了一个大小为5的数组,这意味着它最多可以存储5个元素。然后,使用for-each循环,我们检索所有元素,并借助`length`属性确定给定数组的大小。

示例2

在这个示例中,我们将声明并初始化一个字符串数组。然后,使用for-each循环,我们将打印其元素。最后,借助`length`属性,我们确定给定数组的大小。

import java.util.*;
public class Example2 {
   public static void main(String[] args) {
      // declaration and initialization of the array
      String[] aray = { "Tutorix", "Tutorials", "Point", "Simply", "Easy",
         "Learning"            
         }; 
	  // printing the elements of array
	  System.out.println("Elements of the given array: ");
	  for(String elm : aray) {
	     System.out.print(elm + " "); 
      }
	  System.out.println();
	  // printing the length of array
      System.out.println("Length of the given array: " + aray.length); 
   }
}

输出

Elements of the given array: 
Tutorix Tutorials Point Simply Easy Learning 
Length of the given array: 6

示例3

这是另一个示例,我们将无需使用任何Java的内置属性或方法来查找数组的大小。

方法

  • 声明并初始化两个数组。一个字符串数组和一个整数数组。

  • 然后,定义两个整数类型的计数器变量来存储两个数组的元素计数。

  • 现在,使用for-each循环迭代并在每次迭代中将计数器变量加一。

  • 最后,打印结果并退出。

import java.util.*;
public class Example3 {
   public static void main(String[] args) {
      // declaration and initialization of the arrays
      String[] aray1 = { "Tutorix", "Tutorials", "Point", "Simply", "Easy",
         "Learning"            
         }; 
      int[] aray2 = {58, 66, 74, 55, 62};
      // initial counter variable to store the count of elements
      int countr1 = 0;
      int countr2 = 0;
	  // printing the length of both arrays
	  for(String elm : aray1) {
	     countr1++;
	  }
	  for(int elm : aray2) {
	     countr2++;
	  }
      System.out.println("Length of the String array: " + countr1); 
      System.out.println("Length of the integer array: " + countr2); 
   }
}

输出

Length of the String array: 6
Length of the integer array: 5

结论

在本文中,我们学习了如何使用`length`属性以及示例程序来确定给定数组的大小。此外,我们还讨论了一种无需使用任何内置方法和属性即可查找数组长度的方法。

更新于:2023年7月19日

1K+ 次浏览

启动你的职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.