[Solved] Update concatenated String when other Strings are updated [closed]


Revised

Because strings are immutable their references aren’t copied. To get around this you can use a StringBuffer, but because you want to update a string and have it reflect on another string, your going to need to do some encapsulation of the StringBuffer’s to accomplish it.

class StringChain  {

    private StringBuffer[] buffers;

    public StringChain(StringBuffer[] buffers) {
        this.buffers = buffers;
    }

    public String toString() {
        String finalStr = "";
        for (StringBuffer buf : buffers)
            finalStr += buf;
        return finalStr;
    }
}

And then you can create that object and add StringBuffer’s to it. When you want to get the entire string call the toString method

public static void main(String []args){
    StringBuffer a = new StringBuffer("a"); //Create StringBuffer a
    StringBuffer b = new StringBuffer("b"); //Create StringBuffer b
    StringChain chain = new StringChain(new StringBuffer[] { a, b }); //Pass both buffers to the String Chain
    System.out.println(chain);
    setStringBufferValue(b, "c");
    System.out.println(chain);
 }
 
 private static void setStringBufferValue(StringBuffer buf, String value) {
     buf.replace(0, buf.length(), value);
 }

This will print:

ab

ac

Here is the StringBuilder alternative which is generally recommended over StringBuffer. All that needs to be done is to replace the StringBuffer will StringBuilder instead.

class StringChain  {

    private StringBuilder[] builders;

    public StringChain(StringBuilder[] builders) {
        this.builders = builders;
    }

    public String toString() {
        String finalStr = "";
        for (StringBuilder b : builders)
            finalStr += b;
        return finalStr;
    }
}

....

public static void main(String []args){
    StringBuilder a = new StringBuilder("a"); //Create StringBuilder a
    StringBuilder b = new StringBuilder("b"); //Create StringBuilder b
    StringChain chain = new StringChain(new StringBuilder[] { a, b }); //Pass both builders to the String Chain
    System.out.println(chain);
    setStringBuilderValue(b, "c");
    System.out.println(chain);
 }
 
 private static void setStringBuilderValue(StringBuilder b, String value) {
     b.replace(0, b.length(), value);
 }

7

solved Update concatenated String when other Strings are updated [closed]