software-testing/project_task_sheets/phase_04/project_phase04_tasks/AbstractStringBuilder.java

54 lines
1.5 KiB
Java
Raw Permalink Normal View History

2022-06-08 11:08:26 +02:00
abstract class AbstractStringBuilder {
char value[];
int count;
public AbstractStringBuilder(int capacity) {
value = new char[capacity];
}
public AbstractStringBuilder append(CharSequence s, int start, int end) {
if (s == null)
s = "null";
if ((start < 0) || (end < 0) || (start > end) || (end > s.length()))
throw new IndexOutOfBoundsException(
"start " + start + ", end " + end + ", s.length() "
+ s.length());
int len = end - start;
if (len == 0)
return this;
int newCount = count + len;
if (newCount > value.length)
expandCapacity(newCount);
for (int i=start; i<end; i++)
value[count++] = s.charAt(i);
count = newCount;
return this;
}
void expandCapacity(int minimumCapacity) {
int newCapacity = (value.length + 1) * 2;
if (newCapacity < 0) {
newCapacity = Integer.MAX_VALUE;
} else if (minimumCapacity > newCapacity) {
newCapacity = minimumCapacity;
}
value = Arrays.copyOf(value, newCapacity);
}
public int capacity() {
return value.length;
}
public abstract String toString();
}
class StringBuilder extends AbstractStringBuilder {
public StringBuilder(int capacity) {
super(capacity);
}
public String toString() {
return new String(value, 0, count);
}
}