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

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属性来确定给定数组的大小。此外,我们讨论了一种在不使用任何内置方法和属性的情况下找到数组的长度的方法。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程