Search code examples
javaarraysstringbuilder

Assigning values in StringBuilder array using {}


I can't do this:

StringBuilder[] textArray = new StringBuilder("Word1", "Word2", "Word3", "e.t.c");

Do I do it wrong? Or is it just not possible? Are there better ways?


Solution

  • This is a link to StringBuilder javadoc

    As you can see there is no constructor with a vararg parameter which can accept any number of strings. You can pass only one string to the constructor. But the following example may be what you want:

    new StringBuilder("one string").append("second string").append("third")
    

    but this example will create one string builder. If you want to create one StringBuilder for every string, you can use streams.

            Arrays.stream(new String[]{"one", "second", "third"})
                .map(st -> new StringBuilder(st))
                .toArray();
    

    But this can be to match for smbd who has just started to learn Java.