StringBuilder 未被初始化为给定的长度值

StringBuilder not being initialized to the length value given

我试图创建一个具有给定长度的 StringBuilder 对象,但每次尝试这样做时,StringBuilder 对象的长度都打印为 0。有人知道为什么吗?

String s = "i";
StringBuilder sb = new StringBuilder(s.length()+1);
System.out.println(sb.length());

在上面的代码中,StringBuilder对象的长度应该是2(1从“i”的长度+1),但是当我在Eclipse中打印StringBuilder的长度时,我得到0。我改变了长度到 17 和 100,但我仍然得到 0 作为 sb 的长度。

您没有在该构造函数中设置它的长度。您正在设置它的 capacity 它的长度是 chars 实际上 它的数量,你还没有附加任何

那是因为你设置了StringBuilder的最大容量。长度表示构造字符串的实际大小。让我演示一下:

StringBuilder sb = new StringBuilder(5);
System.out.println("Length after initialization with capacity: " + sb.length());
sb.append("abcd");
System.out.println("Length after appending: " + sb.length());

输出:

Length after initialization with capacity: 0
Length after appending: 4

根据 official documentation for the StringBuilder(int capacity) constructor

Constructs a string builder with no characters in it and an initial capacity specified by the capacity argument.

StringBuilder 实例中还没有字符。它只是根据您传入的 int 参数设置用于存储数据的资源的初始容量。