使用+连接字符串总是一个坏主意 [英] Is it always a bad idea to use + to concatenate strings

查看:128
本文介绍了使用+连接字符串总是一个坏主意的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码如下:

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());
}

这篇关于使用+连接字符串总是一个坏主意的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆