开发者

fixed-length StringBuffer in java

开发者 https://www.devze.com 2023-04-05 21:19 出处:网络
what is the best practise to hold a stringbuffer length fixed in java ? That is if the fixed value is 10and stringbuffer holds ABCDEFGHIJ, when we append K that will cause A to be cleared and resultin

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 comb开发者_JAVA技巧ination but dont know how will its performance be for 100 K length.


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++;
    }
}


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

精彩评论

暂无评论...
验证码 换一张
取 消