Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 534
Richard Brason Avatar asked Dec 06 '25 20:12

Richard Brason


1 Answers

You could so something like this. You would still have to have some overloaded methods to handle different argument counts and types but it wouldn't have to be a full delegation. This is just a simple example. It could be worked into a class. EDIT: Modified to handle most methods.

interface TriConsumer<T,R,S> {
      public void accept(T t, R r, S s);
}
public class StringBuilderSol {
    static int size = 20;
    static StringBuilder sb = new StringBuilder(size);
    
    
    public static void main(String[] args) {

        execute(sb::append, "This is fun!");
        System.out.println(sb);
        execute(sb::append, "Java!");
        System.out.println(sb);
        execute(sb::delete, 0,3);
        execute(sb::replace,0,1,"I");
        execute(sb::insert, 1, " like ");
        execute(sb::delete, 7,15);
        System.out.println(sb);
        execute(sb::append, "time to crash");
        
    }
    
    public static <T> void execute(Consumer<T> con,
            T v) {
        con.accept(v);
        checkLength();
    }
    
    public static <T,R> void execute(
            BiConsumer<T, R> biCon,
            T index, R val) {
        biCon.accept(index, val);
        checkLength();
    }

    public static <T,R,S> void execute(
            TriConsumer<T, R, S> triCon,
            T index, R arg1, S arg2) {
        triCon.accept(index, arg1, arg2);
        checkLength();
    }
    
    public static void checkLength() {
        if (sb.length() > size) {
            throw new IndexOutOfBoundsException();
        }
    }

}

Prints

This is fun!
This is fun!Java!
I like Java!
Exception in thread "main" java.lang.IndexOutOfBoundsException
    at stackOverflow.StringBuilderSol.checkLength(StringBuilderSol.java:50)
    at stackOverflow.StringBuilderSol.execute(StringBuilderSol.java:32)
    at stackOverflow.StringBuilderSol.main(StringBuilderSol.java:25)


Another option (but one that has its own problems) is to set up a timer to periodically check the size of the StringBuilder.

like image 158
WJS Avatar answered Dec 08 '25 09:12

WJS