-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStringBuilder.java
63 lines (52 loc) · 1.19 KB
/
StringBuilder.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
import java.util.Arrays;
public class StringBuilder {
private char[] ary;
private int capacity = 0;
private int chars = 0;
public StringBuilder() {
this(10);
}
public StringBuilder(String initialValue) {
this(initialValue.length() * 2 + 1);
add(initialValue);
}
public StringBuilder(int initialCapacity) {
ary = new char[initialCapacity];
capacity = initialCapacity;
}
public int getCapacity() {
return capacity;
}
public int getLength() {
return chars;
}
public void print() {
System.out.println(new String(ary));
System.out.println(String.format("Length: %d, Capacity: %d",
getLength(), getCapacity()));
}
public void add(String value) {
if (chars + value.length() >= capacity) {
makeBigger();
add(value);
}
else {
for (int i = 0; i < value.length(); i++) {
ary[chars + i] = value.charAt(i);
}
chars += value.length();
}
}
private void makeBigger() {
capacity = (capacity * 2 + 1);
ary = Arrays.copyOf(ary, capacity);
}
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("test");
sb.print();
sb.add("ing stuff. ");
sb.print();
sb.add("The array is about to get much bigger!");
sb.print();
}
}