java中增强for循环的最后一次迭代 [英] Last iteration of enhanced for loop in java

查看:134
本文介绍了java中增强for循环的最后一次迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法确定循环是否是最后一次迭代.我的代码看起来像这样:

Is there a way to determine if the loop is iterating for the last time. My code looks something like this:

int[] array = {1, 2, 3...};
StringBuilder builder = new StringBuilder();

for(int i : array)
{
    builder.append("" + i);
    if(!lastiteration)
        builder.append(",");
}

现在的问题是我不想在最后一次迭代中附加逗号.现在有没有办法确定它是最后一次迭代还是我坚持使用 for 循环或使用外部计数器来跟踪.

Now the thing is I don't want to append the comma in the last iteration. Now is there a way to determine if it is the last iteration or am I stuck with the for loop or using an external counter to keep track.

推荐答案

另一种选择是在附加 i 之前附加逗号,而不是在 第一次 迭代中.(顺便说一下,请不要使用 "" + i - 你真的不想在这里连接,而且 StringBuilder 有一个非常好的 append(int) 重载.)

Another alternative is to append the comma before you append i, just not on the first iteration. (Please don't use "" + i, by the way - you don't really want concatenation here, and StringBuilder has a perfectly good append(int) overload.)

int[] array = {1, 2, 3...};
StringBuilder builder = new StringBuilder();

for (int i : array) {
    if (builder.length() != 0) {
        builder.append(",");
    }
    builder.append(i);
}

这样做的好处是它可以与任何 Iterable 一起使用——你不能总是索引事物.(当您真正使用 StringBuilder 时,添加逗号然后在最后删除它"是一个不错的建议 - 但它不适用于写入流之类的事情.不过,这可能是解决这个确切问题的最佳方法.)

The nice thing about this is that it will work with any Iterable - you can't always index things. (The "add the comma and then remove it at the end" is a nice suggestion when you're really using StringBuilder - but it doesn't work for things like writing to streams. It's possibly the best approach for this exact problem though.)

这篇关于java中增强for循环的最后一次迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆