javastringbuildercharsequence

Is there a class in java similar to StringBuilder with the only difference that it has a fixed length?


Something like this:

MyFixedLengthStringBuilder sb = new MyFixedLengthStringBuilder(2);
sb.append("123"); // <=== throws ArrayIndexOfOutBoundsException!

The rest would be exactly the same. Basically I need a StringBuilder that can never grow.

I see that StringBuilder is final so it can not be extended. Delegation sounds like my only path here. Do you see any other hack/idea/solution for my need?


Solution

  • If I could create my own class, it would go something like this and based on requirements more things could be added

    public class MyFixedLengthStringBuilder {
    
        StringBuilder sb;
        int size;
        
        public MyFixedLengthStringBuilder(int size) {
            if(size < 0)
                throw new IllegalArgumentException();
            this.size = size;
            sb = new StringBuilder(size);
        }
        
        public void append(String str) {
            sb.append(str);
            if(sb.length() > size) {
                sb.setLength(size);
                throw new ArrayIndexOutOfBoundsException();
            }
        }
        
    }