I was asked this in an interview yesterday. I could add whatever methods, members and constructors I wanted but I couldn't change the signature of the provided toString
and append methods.
I implemented something like this:
import java.util.ArrayList;
import java.util.List;
public class StringBuilder {
private List<Character> characterBuffer;
public StringBuilder() {
characterBuffer = new ArrayList<Character>();
}
public void append(String anotherString) {
if(anotherString != null) {
char[] charArray = anotherString.toCharArray();
for(int i=0;i<charArray.length; i++) {
characterBuffer.add(charArray[i]);
}
}
}
public String toString() {
char[] charArray = new char[characterBuffer.size()];
for(int i=0; i<charArray.length; i++) {
charArray[i] = characterBuffer.get(i);
}
return new String(charArray);
}
}
When asked if there was another approach I might have taken, I suggested using a primitive char array buffer that can grow if there is an overflow. Not liking to leave things unfinished, I implemented this solution when I got home:
import java.util.Arrays;
public class StringBuilder {
private char[] characterBuffer;
private int curIndex;
public StringBuilder() {
characterBuffer = new char[5];
curIndex = 0;
}
public void append(String anotherString) {
if(anotherString != null) {
char[] charArray = anotherString.toCharArray();
int charArrayLength = charArray.length;
if(overflow(charArrayLength)) {
characterBuffer = Arrays.copyOf(characterBuffer, newLength(charArrayLength));
}
for(int i=0;i<charArray.length; i++) {
characterBuffer[curIndex++] = charArray[i];
}
}
}
private int newLength(int arrayLength) {
return (characterBuffer.length + arrayLength) + 10;
}
private boolean overflow(int arrayLength) {
return (arrayLength + curIndex) > characterBuffer.length;
}
public String toString() {
return new String(characterBuffer, 0, curIndex);
}
}
I'd like both approaches reviewed.