使用 + 连接字符串总是一个坏主意吗

我的代码如下:

String s = "";
for (My my : myList) {
    s += my.getX();
}

当我这样做时,Findbugs 总是报告错误.

Findbugs always reports error when I do this.

推荐答案

如果你手动连接,我会使用 +

I would use + if you are manually concatenating,

String word = "Hello";
word += " World!";

但是,如果您要迭代和连接,我建议 StringBuilder,

However, if you are iterating and concatenating I would suggest StringBuilder,

StringBuilder sb = new StringBuilder();
for (My my : myList) {
    sb.append(my.getX());
}

相关文章