Using a comma is just to make it specific - it could be any delimiter, so using List's default toString() doesn't help. (The question could be rephrased as: "best way to implement List's toString?")
This is a well-known problem, and I know several ways of doing it, but I'm wondering what the best way is (where "best" means clearest and/or shortest, not most efficient).
The problem as a story: I have a list. I want to loop over it, printing each value. I want to print a comma between each item - but not after the last one (nor before the first one).
The problem as a grammar (edit: added second alternative):
List --> Item ( , Item ) *
List --> ( Item , ) * Item
Sample solution 1:
boolean isFirst = true;
for (Item i : list) {
if (isFirst) {
System.out.print(i); // no comma
isFirst = false;
} else {
System.out.print(", "+i); // comma
}
}
Sample solution 2 - create a sublist:
if (list.size()>0) {
System.out.print(list.get(0)); // no comma
List theRest = list.subList(1, list.size());
for (Item i : theRest) {
System.out.print(", "+i); // comma
}
}
Sample solution 3:
Iterator<Item> i = list.iterator();
if (i.hasNext()) {
System.out.print(i.next());
while (i.hasNext())
System.out.print(", "+i.next());
}
These treat the first item specially; one could instead treat the last one specially.
Incidentally, here is how List toString is implemented (it's inherited from AbstractCollection), in Java 1.6:
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(", ");
}
}
It exits the loop early to avoid the comma after the last item. BTW: this is the first time I recall seeing "(this Collection)"; here's code to provoke it:
List l = new LinkedList();
l.add(l);
System.out.println(l);
I welcome any solution, even if they use unexpected libraries (regexp?); and also solutions in languages other than Java (e.g. I think Python/Ruby have an intersperse function - how is that implemented?).
Clarification: by libraries, I mean the standard Java libraries. For other libraries, I consider them with other languages, and interested to know how they're implemented.
EDIT toolkit mentioned a similar question: http://stackoverflow.com/questions/285523/last-iteration-of-for-loop-in-java
And another: http://stackoverflow.com/questions/156650/does-the-last-element-in-a-loop-deserve-a-separate-treatment