ArrayList
eredita la sua toString()
-Metodo da AbstractCollection
, vale a dire:
public String toString() {
Iterator<E> i = iterator();
if (! i.hasNext())
return "[]";
StringBuilder sb = new StringBuilder();
sb.append('[');
for (;;) {
E e = i.next();
sb.append(e == this ? "(this Collection)" : e);
if (! i.hasNext())
return sb.append(']').toString();
sb.append(", ");
}
}
Costruire la stringa da soli sarà molto più efficiente.
Se davvero si vuole aggregare le stringhe in anticipo in una sorta di lista, è necessario fornire il proprio metodo per accedere in modo efficiente loro, ad esempio, In questo modo:
static String join(Collection<?> items, String sep) {
if(items.size() == 0)
return "";
String[] strings = new String[items.size()];
int length = sep.length() * (items.size() - 1);
int idx = 0;
for(Object item : items) {
String str = item.toString();
strings[idx++] = str;
length += str.length();
}
char[] chars = new char[length];
int pos = 0;
for(String str : strings) {
str.getChars(0, str.length(), chars, pos);
pos += str.length();
if(pos < length) {
sep.getChars(0, sep.length(), chars, pos);
pos += sep.length();
}
}
return new String(chars);
}
Sono d'accordo sul fatto che non mi piace il modo in cui l'OP lo fa, ma per ragioni diverse. (1) Facendolo in questo modo si nasconde l'intento del codice (mentre qualcosa come "StringUtils.join" è perfettamente leggibile). (2) Non è flessibile, poiché potresti voler cambiare il delimitatore. (Sostituire semplicemente '", "' nella stringa finale non è un buon modo, dal momento che potrebbe esserci '", "' incorporato nelle stringhe originali.) Quindi anche se, come dici tu, 'ArrayList.toString' probabilmente ha vinto Cambiare, non vorrei ancora seguire questa strada. –
Puoi essere sicuro al 99,9% che ArrayList.toString non cambierà a meno che non diventi un vettore di attacco in qualche modo; la retrocompatibilità lo vedrà. Ma sono d'accordo che l'uso di toString() è ancora una cattiva idea. –