专注Java教育14年 全国咨询/投诉热线:444-1124-454
星辉LOGO图
始于2009,口口相传的Java黄埔军校
首页 学习攻略 Java学习 Java中查找数组的长度

Java中查找数组的长度

更新时间:2022-09-29 11:25:57 来源:星辉 浏览2275次

在Java中,数组长度是数组可以容纳的元素数。没有预定义的方法来获取数组的长度。我们可以使用数组属性长度在Java中找到数组长度。我们将此属性与数组名一起使用。在本节中,我们将学习如何在Java中查找数组的长度或大小。

数组长度属性

Java提供了一个属性长度,用于确定数组的长度。每个数组都有一个内置长度属性,其值为数组的大小。Size表示数组可以包含的元素总数。可以使用点(.)运算符后跟数组名称来调用length属性。我们可以找到int[]、double[]、String[]等的长度。例如:

int[] arr=new int[5];  
int arrayLength=arr.length  

在上面的代码片段中,arr是一个int类型的数组,可以容纳5个元素。arrayLength是存储数组长度的变量。为了找到数组的长度,我们分别使用了数组名(arr),后跟点运算符和长度属性。它决定数组的大小。

请注意,长度决定了数组可以包含的最大元素数或数组的容量。它不计算插入数组的元素。也就是说,length返回数组的总大小。对于其元素在创建时初始化的数组,长度和大小是相同的。

如果我们讨论逻辑大小,数组的索引,那么只需intarrayLength=arr。长度为-1,因为数组索引从0开始。因此,逻辑或数组索引总是小于实际大小1。

让我们通过一个例子来找到数组的长度。

例子1

public class ArrayLengthExample1  
{   
public static void main(String[] args)   
{   
//defining an array of type int named num  
//the square bracket contain the length of an array  
int[] num = new int[10];   
//length is an Array attribute that determines the array length   
int arrayLength=num.length;  
//prints array length  
System.out.println("The length of the array is: "+ arrayLength);   
}   
}  

输出:

The length of the array is: 10

例子2

public class ArrayLengthExample2   
{   
public static void main(String[] args)   
{   
//initializing an array of type String named country   
String[] country = { "India", "Australia", "Japan", "USA", "UAE", "Canada", "Brazil"};  
//length is an Array attribute that determines the array length   
int arrayLength=country.length;   
//prints array length  
System.out.println("The size of the array is: " + arrayLength);   
}   
}  

输出:

The size of the array is: 7

例子3

public class ArrayLengthExample3   
{  
private static void LengthOfArray(String[] array)   
{  
//checks array is empty or not      
if (array == null)   
{  
//if the array is empty prints the following statement  
System.out.println("The array is empty, can't be determined length.");  
}   
else   
{  
//length attribute of the Array class determines the length of an array  
int arrayLength = array.length;  
//prints the array length  
System.out.println("The length of the array is: "+arrayLength);  
}  
}  
public static void main(String[] args)   
{  
String[] fruits = { "Guava", "Banana", "Apple", "Papaya", "Melon", "Strawberry"};  
String[] alphabets = { "m", "p", "k", "l", "t" };  
String[] numbers = { "12", "25", "63", "84", "90", "11", "54"};  
//passing null value to the function  
LengthOfArray(null);  
//passing fruits array to the function  
LengthOfArray(fruits);  
//passing alphabets array to the function  
LengthOfArray(alphabets);  
//passing numbers array to the function  
LengthOfArray(numbers);  
}  
}  

输出

The array is empty, can't be determined length.
The length of the array is: 6
The length of the array is: 5
The length of the array is: 7

 

提交申请后,顾问老师会电话与您沟通安排学习

免费课程推荐 >>
技术文档推荐 >>