Java: StringBuffer & Concatenation

后端 未结 6 2031
梦如初夏
梦如初夏 2021-01-05 01:59

I\'m using StringBuffer in Java to concat strings together, like so:

StringBuffer str = new StringBuffer();

str.append(\"string value\");

6条回答
  •  一生所求
    2021-01-05 02:24

    I think this is handled easier either with a helper method (untested code):

    public String myMethod() {
        StringBuilder sb = new StringBuilder();
        addToBuffer(sb, "Hello").addToBuffer("there,");
        addToBuffer(sb, "it").addToBuffer(sb, "works");
    }
    
    private StringBuilder addToBuffer(StringBuilder sb, String what) {
        return sb.append(what).append(' ');  // char is even faster here! ;)
    }
    

    Or even using a Builder pattern with a fluent interface (also untested code):

    public String myMethod() {
        SBBuilder builder = new SBBuilder()
            .add("Hello").add("there")
            .add("it", "works", "just", "fine!");
    
        for (int i = 0; i < 10; i++) {
            builder.add("adding").add(String.valueOf(i));
        }
    
        System.out.println(builder.build());
    }
    
    public static class SBBuilder {
        private StringBuilder sb = new StringBuilder();
    
        public SBBuilder add(String... parts) {
            for (String p : parts) {
                sb.append(p).append(' '); // char is even faster here! ;)
            }
            return this;
        }
    
        public String build() {
            return sb.toString();
        }
    }
    

    Here's an article on the subject.

    Hope it helps! :)

提交回复
热议问题