开发者

How to print a list with a different separator from the comma?

开发者 https://www.devze.com 2023-01-20 17:09 出处:网络
I keep on copy-pasting the following in my programs. I\'m wondering if anyone of you uses similar code, perhaps in a library to achieve the same.

I keep on copy-pasting the following in my programs. I'm wondering if anyone of you uses similar code, perhaps in a library to achieve the same.

@Override
public String toString() {
    String ret = prefix;
    boolean first = true;

    for (Component child : children) {
        if (!first) {
            ret += " " + separator + " ";
        } else {
            first = false;
        }
        ret += child.getName();
    }
    retu开发者_JAVA百科rn ret + postfix;
}

PS: One could use StringBuilder instead of String. Got that.


Apache commons provides a number of join methods in the StringUtils class.

This page also has a lot of interesting suggestions on the best way to implement such a method: http://snippets.dzone.com/posts/show/91


Nope. The only thing I can think of is it abstract that " " away into a final field in the toString() function. The reason that we don't have anything nicer is because the foreach construct doesn't care about the position, only that it will print sequentially.

That being said, avoid copy and paste at all costs. Make your own library if need be. Allow it to take a parameter of an interface which indicates if it is the first, and go from there.

0

精彩评论

暂无评论...
验证码 换一张
取 消