StringBuilder vs String concatenation in toString() in Java

后端 未结 18 2308
北恋
北恋 2020-11-21 04:18

Given the 2 toString() implementations below, which one is preferred:

public String toString(){
    return \"{a:\"+ a + \", b:\" + b + \", c: \"         


        
18条回答
  •  故里飘歌
    2020-11-21 04:45

    Can I point out that if you're going to iterate over a collection and use StringBuilder, you may want to check out Apache Commons Lang and StringUtils.join() (in different flavours) ?

    Regardless of performance, it'll save you having to create StringBuilders and for loops for what seems like the millionth time.

提交回复
热议问题