Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fixed-length StringBuffer in java

what is the best practise to hold a stringbuffer length fixed in java ? That is if the fixed value is 10 and stringbuffer holds ABCDEFGHIJ, when we append K that will cause A to be cleared and resulting value will be BCDEFGHIJK.I am thinking to use StringBuffer's reverse() and and setLenght() method combination but dont know how will its performance be for 100 K length.

like image 659
cacert Avatar asked Sep 18 '11 12:09

cacert


People also ask

How do I determine the length of a StringBuffer?

To find the length of the StringBuffer object, the length() function is used. It is a method of the StringBuffer Class. The method returns the count of characters in the sequence.

What is Java buffer length?

The java. lang. StringBuffer. length() method returns the length (character count) of the sequence of characters currently represented by this object.

What is the maximum size of StringBuffer in Java?

Java StringBuffer capacity() method An empty StringBuffer class contains the default 16 character capacity.

Why is StringBuffer not immutable?

We all know that the String class in Java is mutable i.e. once we create a String variable we cannot modify its data or do any manipulations. But, there may be scenarios where we need to modify the data of String variables. In such cases, we could use StringBuffer class. is like a String, but can be modified.


1 Answers

It sounds like you're after a circular buffer. You could create a char[] and maintain a size as well as the logical start. Then when you need to convert it into a string, you can just create two strings (one from the end of the buffer and one from the start) and concatenate them together. That will be relatively expensive though - try to keep it just as the circular buffer for as much of the time as you can.

Make sure that on each operation you also consider the possibility of the buffer not being full though. Sample operation:

public void append(char c)
{
    buffer[(size + start) % maxLength] = c;
    if (size == maxLength)
    {
        start = (start + 1) % maxLength;
    }
    else
    {
        size++;
    }
}
like image 98
Jon Skeet Avatar answered Sep 30 '22 21:09

Jon Skeet