如何在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`屬性以及示例程式來確定給定陣列的大小。此外,我們還討論了一種無需使用任何內建方法和屬性即可查詢陣列長度的方法。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP