Java 中長度和容量的區別
在 Java 中,術語“長度”和“容量”與集合(如陣列、字串和 ArrayList)中元素的儲存有關。長度指的是當前儲存在給定集合中的元素數量,而容量指的是集合可以容納的最大元素數量。在本文中,我們將探討 Java 中長度和容量之間的區別。
Java 中的長度與容量
長度
要獲取陣列的長度,我們使用其“length”屬性,可以使用其內建方法“length()”獲取字串的長度。對於陣列,length 屬性將計算其中儲存的元素數量;對於字串,“length()”方法將計算其包含的字元數量。
示例 1
以下示例說明了如何使用 length 屬性與陣列。
public class Example1 { public static void main(String[] args) { int[] aray = new int[10]; // declaring array of size 10 // initializing the array aray[0] = 1; aray[1] = 2; aray[2] = 3; // printing the length of array System.out.println("Length of the given array: " + aray.length); } }
輸出
Length of the given array: 10
在上面的程式碼中,我們聲明瞭一個大小為 10 的陣列,這意味著它最多可以儲存 10 個元素。由於陣列是固定大小的,因此陣列的長度和容量在 Java 中始終相等。
示例 2
在以下示例中,我們將使用 length() 方法檢查字串的長度。
public class Example2 { public static void main(String[] args) { // declaration and initialization of strings String st1 = "Tutorialspoint"; String st2 = "Tutorix"; // printing the length of strings System.out.println("Length of the String 1: " + st1.length()); System.out.println("Length of the given String 2: " + st2.length()); } }
輸出
Length of the String 1: 14 Length of the given String 2: 7
容量
由於字串是不可變的,Java 提供了 StringBuffer 和 StringBuilder 類,用於修改字串。要獲取這些類的容量,我們使用名為“capacity()”的內建方法。預設情況下,它們有能力容納 16 個字元。因此,當我們在這些類中儲存任何字串時,結果將比字串的實際長度多 16 個。
示例 2
以下示例演示瞭如何使用“capacity()”。
public class Example3 { public static void main(String[] args) { // initializing the string String st1 = "Tutorialspoint"; // passing the string to StringBuilder object StringBuilder st2 = new StringBuilder(st1); // printing the length and capacity System.out.println("Length of the st1: " + st1.length()); System.out.println("Length of the st2: " + st2.length()); System.out.println("Capacity of st2: " + st2.capacity()); } }
輸出
Length of the st1: 14 Length of the st2: 14 Capacity of st2: 30
長度和容量之間的區別
根據以上討論,我們可以得出長度和容量之間的以下區別:−
Length() |
Capacity() |
---|---|
它是 String 類的 方法。 |
它是 StringBuilder 和 StringBuffer 類的 方法 |
空字串的初始長度為 0。 |
StringBuilder 和 StringBuffer 類的初始容量均為 16 |
它檢查字串中字元的總數 |
它檢查集合可以容納的最大元素數量 |
當我們複製字串時,會考慮其長度。 |
複製時不考慮它 |
結論
Java 中長度和容量之間存在細微差別,我們可以說兩者相互補充。雖然兩者都與元素的儲存有關,但長度是字元或元素的總數,而容量表示容納最大元素數量的能力。