C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
And: It prints out the length, and the capacity on each iteration. We see how the capacity changes.
Java program that measures capacity after appends
import java.lang.StringBuilder;
public class Program {
public static void main(String[] args) {
StringBuilder builder = new StringBuilder("");
for (int i = 0; i < 20; i++) {
// Print length and capacity.
System.out.println("Length = " + builder.length() +
"; Capacity = "
+ builder.capacity());
// Add 5 chars to StringBuilder.
builder.append("xxxyy");
}
}
}
Output
Length = 0; Capacity = 16
Length = 5; Capacity = 16
Length = 10; Capacity = 16
Length = 15; Capacity = 16
Length = 20; Capacity = 34
Length = 25; Capacity = 34
Length = 30; Capacity = 34
Length = 35; Capacity = 70
Length = 40; Capacity = 70
Length = 45; Capacity = 70
Length = 50; Capacity = 70
Length = 55; Capacity = 70
Length = 60; Capacity = 70
Length = 65; Capacity = 70
Length = 70; Capacity = 70
Length = 75; Capacity = 142
Length = 80; Capacity = 142
Length = 85; Capacity = 142
Length = 90; Capacity = 142
Length = 95; Capacity = 142