Fixed-length StringBuffer in java

What is the best practice for keeping stringbuffer length fixed in java? That is, if the fixed value is 10, and the stringbuffer contains ABCDEFGHIJ, when we add K, which will clear A, and the final value will be BCDEFGHIJK. I am thinking of using a combination of the StringBuffer reverse () and setLenght () methods, but I don’t know how its performance will be 100 K.

+4
source share
2 answers

You can use delete :

void append(String s) { buffer.append(s); if(buffer.length() > MAX_LENGTH){ buffer.delete(0, buffer.length() - MAX_LENGTH); } } 

Update . If the parameter is a long string, this results in unnecessary selection of StringBuffer. To avoid this, you can first reduce the buffer and then add only as many line characters as necessary:

 void append(String s) { if (buffer.length() + s.length() > MAX_LENGTH) { buffer.delete(0, buffer.length() + s.length() - MAX_LENGTH); } buffer.append(s, Math.max(0, s.length() - MAX_LENGTH), s.length()); } 
+2
source

It looks like you are after a circular buffer. You can create char[] and save the size, as well as a logical start. Then, when you need to convert it to a string, you can simply create two lines (one from the end of the buffer and one from the very beginning) and combine them together. It will be relatively expensive - try to save it as a round buffer for as long as you can.

Make sure that each operation also takes into account the possibility that the buffer will not be full. Work with a sample:

 public void append(char c) { buffer[(size + start) % maxLength] = c; if (size == maxLength) { start = (start + 1) % maxLength; } else { size++; } } 
+9
source

All Articles