Assume you have a fixed length string buffer, and implement a circular queue kind of functionality using it.
Example
String buffer with size 5 can hold 5 characters ABCDE, When I append new character ‘F’ to the existing string buffer, the resukting buffer should be BCDEF.
We can achieve this functionality using StringBuffer delete and append methods.
public StringBuffer delete(int start, int end)
Removes the characters in a substring of this sequence. The substring begins at the specified start and extends to the character at index end - 1 or to the end of the sequence if no such character exists. If start is equal to end, no changes are made.
public StringBuffer append(CharSequence s)
Appends the specified CharSequence to this sequence.
Example
Find the below working application.
CircularStringBuffer.java
package com.sample.app;
import java.util.StringJoiner;
public class CircularStringBuffer {
private final int maxLength;
private final StringBuffer stringBuffer;
public CircularStringBuffer(int length) {
if (length <= 0) {
length = 10;
}
this.stringBuffer = new StringBuffer(length);
this.maxLength = length;
}
void append(final String input) {
final int bufferLength = stringBuffer.length();
final int inputLength = input.length();
if (bufferLength + inputLength > maxLength) {
stringBuffer.delete(0, bufferLength + inputLength - maxLength);
}
stringBuffer.append(input, Math.max(0, inputLength - maxLength), inputLength);
}
@Override
public String toString() {
final StringJoiner joiner = new StringJoiner("->");
for (char ch : stringBuffer.toString().toCharArray()) {
joiner.add("" + ch);
}
return joiner.toString();
}
}
App.java
package com.sample.app;
public class App {
public static void main(String[] args) {
CircularStringBuffer circularBuffer = new CircularStringBuffer(5);
circularBuffer.append("A");
System.out.println(circularBuffer);
circularBuffer.append("B");
System.out.println(circularBuffer);
circularBuffer.append("C");
System.out.println(circularBuffer);
circularBuffer.append("D");
System.out.println(circularBuffer);
circularBuffer.append("E");
System.out.println(circularBuffer);
circularBuffer.append("F");
System.out.println(circularBuffer);
circularBuffer.append("G");
System.out.println(circularBuffer);
circularBuffer.append("H");
System.out.println(circularBuffer);
}
}
Output
A A->B A->B->C A->B->C->D A->B->C->D->E B->C->D->E->F C->D->E->F->G D->E->F->G->H
No comments:
Post a Comment