Skip to main content
Code Review

Return to Revisions

3 of 4
replaced http://codereview.stackexchange.com/ with https://codereview.stackexchange.com/

I presume lines is a Collection of some sort. One option that has slightly less of a smell (although it still is odoriferous), is to use an iterator, which will essentially do the same work, but will be more readable:

for (Iterator<String> it = lines.iterator(); it.hasNext();) {
 writer.write(it.next());
 if (it.hasNext()) {
 writer.newline();
 }
}

As I say, all this does is make it more readable....

Other options are to duplicate the write - once in the loop, and then the last one outside the loop:

if (!lines.isEmpty()) {
 int limit = lines.size() - 1;
 for (int i = 0; i < limit; i++) {
 ....
 }
 writer.write(lines.get(limit));
}

EDIT: @tomdemuyt suggested reversing the newline to happen only after the first line as follows:

if (!lines.isEmpty()) {
 writer.write(lines.get(0));
 // start index at 1 instead of 0.
 for (int i = 1; i < lines.size(); i++) {
 writer.newline();
 writer.write(lines.get(limit));
 }
}
rolfl
  • 98.1k
  • 17
  • 219
  • 419
default

AltStyle によって変換されたページ (->オリジナル) /