0%

java_可变字符串

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// 2.21
// 可变字符串:可变字符串在追加、删除、修改、插入和拼接等操作时不会产生新的对象
// Java中提供了两个可变字符串类型,StringBuffer and StringBuilder,中文翻译为字符串缓冲区
// 理解:字符串长度和字符串缓冲区
// 字符串长度和字符串缓冲区容量区别。字符串长度是指在字符串缓冲区中目前所包含字符 串长度,
// 通过length()获得;字符串缓冲区容量是缓冲区中所能容纳的最大字符数,通过capacity() 获得。
// 当所容纳的字符超过这个长度时,字符串缓冲区自动扩充容量,但这是以牺牲性能为代价 的扩容。
// 字符串长度和字符串缓冲区容量示例代码:
StringBuilder nameString = new StringBuilder();
System.out.println(nameString.length());
System.out.println(nameString.capacity());//长度为零,而容量为16

StringBuilder nameString1 = new StringBuilder("xiaolei");
System.out.println(nameString1.length());
System.out.println(nameString1.capacity());//长度为7,而容量为16

//字符串缓冲区初始容量是16,超过之后会扩容,现在通过一个for循环来证明这个事情
StringBuilder teStringBuilder = new StringBuilder();
for(int i = 0;i < 17;i++) {
teStringBuilder.append(8);
System.out.println("包含的字符串长度为:" + teStringBuilder.length());
System.out.println("字符串缓冲区容量为:" + teStringBuilder.capacity());
}
//由输出结果我们可以看到,最后当字符串长度为17的时候,字符串缓冲区的容量变成了34

// 字符串追加——append
// 添加字符串
StringBuilder stringBuilder = new StringBuilder();
System.out.println(stringBuilder.append("Hello").append(" ").append("World!"));
// 添加布尔值,转义符和空对象
StringBuffer stringBuffer = new StringBuffer();
Object object = null;
System.out.println(stringBuffer.append(false).append("\t").append(object));
// 添加数值
StringBuffer numBuffer = new StringBuffer();
int i = 0;
while (i < 10) {
numBuffer.append(i);
i++;
System.out.println(numBuffer);

}
/*Output
* 0
16
7
23
包含的字符串长度为:1
字符串缓冲区容量为:16
包含的字符串长度为:2
字符串缓冲区容量为:16
包含的字符串长度为:3
字符串缓冲区容量为:16
包含的字符串长度为:4
字符串缓冲区容量为:16
包含的字符串长度为:5
字符串缓冲区容量为:16
包含的字符串长度为:6
字符串缓冲区容量为:16
包含的字符串长度为:7
字符串缓冲区容量为:16
包含的字符串长度为:8
字符串缓冲区容量为:16
包含的字符串长度为:9
字符串缓冲区容量为:16
包含的字符串长度为:10
字符串缓冲区容量为:16
包含的字符串长度为:11
字符串缓冲区容量为:16
包含的字符串长度为:12
字符串缓冲区容量为:16
包含的字符串长度为:13
字符串缓冲区容量为:16
包含的字符串长度为:14
字符串缓冲区容量为:16
包含的字符串长度为:15
字符串缓冲区容量为:16
包含的字符串长度为:16
字符串缓冲区容量为:16
包含的字符串长度为:17
字符串缓冲区容量为:34
Hello World!
false null
0
01
012
0123
01234
012345
0123456
01234567
012345678
0123456789
*/