5

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.

2 Answers 2

10

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++;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

You could 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 StringBuffer allocations. To avoid this, you could shorten the buffer first, and then append only as much characters of the string as needed:

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());
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.