Java 中长度和容量的区别


在 Java 中,术语“长度”和“容量”与集合(如数组、字符串和 ArrayList)中元素的存储有关。长度指的是当前存储在给定集合中的元素数量,而容量指的是集合可以容纳的最大元素数量。在本文中,我们将探讨 Java 中长度和容量之间的区别。

Java 中的长度与容量

长度

要获取数组的长度,我们使用其“length”属性,可以使用其内置方法“length()”获取字符串的长度。对于数组,length 属性将计算其中存储的元素数量;对于字符串,“length()”方法将计算其包含的字符数量。

示例 1

以下示例说明了如何使用 length 属性与数组。

Open Compiler
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() 方法检查字符串的长度。

Open Compiler
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()”。

Open Compiler
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

它检查字符串中字符的总数

它检查集合可以容纳的最大元素数量

当我们复制字符串时,会考虑其长度。

复制时不考虑它

Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

结论

Java 中长度和容量之间存在细微差别,我们可以说两者相互补充。虽然两者都与元素的存储有关,但长度是字符或元素的总数,而容量表示容纳最大元素数量的能力。

更新时间: 2023-07-21

488 次查看

开启您的 职业生涯

通过完成课程获得认证

开始学习
广告