Frank M.
Frank M.

Reputation: 997

Using StringBuilder with double brace initialization

double brace initialization is good for have better visibility of the context of java code.

unfortunately StringBuilder can't use with double brace initialization like

    final String[] array = new String[] {"A", "B"};
    System.out.println(new StringBuilder(){{
                           for (String s : array){
                               append(s + "\n");
                           }
                       }}.toString());

is this a good alternative? any better suggestions? my intention for this question is not to find a way for string concatination. my intention is to find a way for use double brace with StringBuilder.

    final String[] array = new String[] {"A", "B"};
    System.out.println(new Object(){
        @Override public String toString(){
            StringBuilder stringBuilder = new StringBuilder();
            for (String s : array){
                stringBuilder.append(s + "\n");
            }
            return stringBuilder.toString();
        }
    });

Upvotes: -1

Views: 322

Answers (3)

afzalex
afzalex

Reputation: 8652

Alternative method is not acceptable because it changed the class of StringBuilder object.

In your program first option is not working because StringBuilder is final. And you cannot change a final class. You can use the following code which will work in all situations.

    final String[] array = {"a", "b"};
    StringBuilder sb = new StringBuilder(new Object(){
        @Override
        public String toString() {
            String str = "";
            for(String st : array){
                str+=st;
            }
            return str;
        }
    }.toString());
    System.out.println(sb);

Upvotes: 0

Frank M.
Frank M.

Reputation: 997

with a extra utility class is double brace initialization possible. with

public static class StringBuild{
    private StringBuilder stringBuilder = new StringBuilder();

    public void append(String string){
        stringBuilder.append(string);
    }

    @Override
    public String toString(){
        return stringBuilder.toString();
    }
}

can i write

    final String[] array = new String[] {"A", "B"};
    System.out.println(new StringBuild(){{
            for (String s : array){
                append(s + "\n");
            }
        }
    });

Upvotes: 0

Boris
Boris

Reputation: 24443

If what you are trying to achieve is just creating a string from an array of strings, you can use Arrays.toString() method:

System.out.println(Arrays.toString(array));

This method returns a string representation of the contents of the specified array.

Upvotes: 0

Related Questions