Search code examples
javastringbuffer

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.


Solution

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