JavaParser Source Viewer

Home|JavaParser/com/github/javaparser/utils/SeparatedItemStringBuilder.java
1/*
2 * Copyright (C) 2007-2010 JĂșlio Vilmar Gesser.
3 * Copyright (C) 2011, 2013-2020 The JavaParser Team.
4 *
5 * This file is part of JavaParser.
6 *
7 * JavaParser can be used either under the terms of
8 * a) the GNU Lesser General Public License as published by
9 *     the Free Software Foundation, either version 3 of the License, or
10 *     (at your option) any later version.
11 * b) the terms of the Apache License
12 *
13 * You should have received a copy of both licenses in LICENCE.LGPL and
14 * LICENCE.APACHE. Please refer to those files for details.
15 *
16 * JavaParser is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 * GNU Lesser General Public License for more details.
20 */
21
22package com.github.javaparser.utils;
23
24/**
25 * Builds a string containing a list of items with a prefix, a postfix, and a separator.
26 * <br>Example: (1,2,3) which has prefix "(", separator ",", postfix ")" and the items 1 through 3.
27 * <p/>Java 8 offers the very nice Collectors.joining(String, String, String) which does the same thing.
28 */
29public class SeparatedItemStringBuilder {
30    private final String separator;
31    private final String postfix;
32    private boolean hasItems = false;
33    private StringBuilder builder;
34
35    public SeparatedItemStringBuilder(String prefixString separatorString postfix) {
36        builder = new StringBuilder(prefix);
37        this.separator = separator;
38        this.postfix = postfix;
39
40    }
41
42    /**
43     * Add one item. Either pass a string, or a format for String.format and corresponding arguments.
44     */
45    public SeparatedItemStringBuilder append(CharSequence formatObject... args) {
46        if (hasItems) {
47            builder.append(separator);
48        }
49        builder.append(String.format(format.toString(), args));
50        hasItems = true;
51        return this;
52    }
53
54    public boolean hasItems() {
55        return hasItems;
56    }
57
58    /**
59     * Convert the builder into its final string representation.
60     */
61    @Override
62    public String toString() {
63        // This order of toStringing avoids debuggers from making a mess.
64        return builder.toString() + postfix;
65    }
66}
67
MembersX
SeparatedItemStringBuilder:builder
SeparatedItemStringBuilder:postfix
SeparatedItemStringBuilder:hasItems
SeparatedItemStringBuilder:SeparatedItemStringBuilder
SeparatedItemStringBuilder:separator
SeparatedItemStringBuilder:append
SeparatedItemStringBuilder:toString
Members
X