String s = "";
for (Person p : persons) {
s += ", " + p.getName();
}
s = s.substring(2); //remove first comma
正确的写法:
StringBuilder sb = new StringBuilder(persons.size() * 16); // well estimated buffer
for (Person p : persons) {
if (sb.length() > 0) sb.append(", ");
sb.append(p.getName);
}
错误的使用StringBuffer
错误的写法:
StringBuffer sb = new StringBuffer();
sb.append("Name: ");
sb.append(name + '\n');
sb.append("!");
...
String s = sb.toString();