Last iteration of enhanced for loop in java -
is there way determine if loop iterating last time. code looks this:
int[] array = {1, 2, 3...}; stringbuilder builder = new stringbuilder(); for(int : array) { builder.append("" + i); if(!lastiteration) builder.append(","); }
now thing don't want append comma in last iteration. there way determine if last iteration or stuck loop or using external counter keep track.
another alternative append comma before append i, not on first iteration. (please don't use "" + i
, way - don't want concatenation here, , stringbuilder has append(int) overload.)
int[] array = {1, 2, 3...}; stringbuilder builder = new stringbuilder(); (int : array) { if (builder.length() != 0) { builder.append(","); } builder.append(i); }
the nice thing work iterable
- can't index things. (the "add comma , remove @ end" nice suggestion when you're using stringbuilder - doesn't work things writing streams. it's possibly best approach exact problem though.)
Comments
Post a Comment