This section provides a tutorial example on how to implement a simple string buffer class similar to the StringBuffer class included in the java.lang package.
In order to better understand the StringBuffer class, I wrote the following
program, SimpleStringBuffer, which implements a really simple string buffer
class with only one append() method:
/**
* SimpleStringBuffer.java
* Copyright (c) 2003 by Dr. Herong Yang
*/
public class SimpleStringBuffer {
private char[] buffer;
private int capacity;
private int length;
public SimpleStringBuffer() {
this(16);
}
public SimpleStringBuffer(int l) {
capacity = l;
buffer = new char[capacity];
length = 0;
}
public synchronized SimpleStringBuffer append(String str) {
String s = str;
if (s==null) s = "null";
if (length+s.length()>capacity) {
int l = Math.max(length+s.length(), 2*capacity);
char[] b = new char[l];
for (int i=0; i<length; i++) {
b[i] = buffer[i];
}
buffer = b;
capacity = l;
}
for (int i=0; i<s.length(); i++) {
buffer[length+i] = s.charAt(i);
}
length += s.length();
return this;
}
public String toString() {
return new String(buffer, 0, length);
}
Several notes on this class:
I used a character array "char[]" as the storage for the string buffer.
Two constructor methods are provided: one takes the default buffer capacity of 16 characters,
and the other allows the caller to specify a specific capacity.
The main method is append(), which appends the specified string to the end of the buffer.
If there are not enough free spaces in the buffer to append the specified string,
the buffer will be extended with a higher capacity.
See the next section for testing result of this class.