java中增强for循环的最后一次迭代
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/285523/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Last iteration of enhanced for loop in java
提问by Mercurious
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(",");
}
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.
现在的问题是我不想在最后一次迭代中附加逗号。现在有没有办法确定它是否是最后一次迭代,或者我是否坚持使用 for 循环或使用外部计数器来跟踪。
回答by Dinah
It might be easier to always append. And then, when you're done with your loop, just remove the final character. Tons less conditionals that way too.
总是附加可能更容易。然后,当您完成循环时,只需删除最后一个字符。这样也少了很多条件。
You can use StringBuilder
's deleteCharAt(int index)
with index being length() - 1
您可以将StringBuilder
'sdeleteCharAt(int index)
与 index 一起使用length() - 1
回答by sblundy
If you convert it to a classic index loop, yes.
如果将其转换为经典的索引循环,是的。
Or you could just delete the last comma after it's done. Like so:
或者您可以在完成后删除最后一个逗号。像这样:
int[] array = {1, 2, 3...};
StringBuilder
builder = new StringBuilder();
for(int i : array)
{
builder.append(i + ",");
}
if(builder.charAt((builder.length() - 1) == ','))
builder.deleteCharAt(builder.length() - 1);
Me, I just use StringUtils.join()
from commons-lang.
我,我只是使用StringUtils.join()
from commons-lang。
回答by Gareth Davis
keep it simple and use a standard for loop:
保持简单并使用标准 for 循环:
for(int i = 0 ; i < array.length ; i ++ ){
builder.append(array[i]);
if( i != array.length - 1 ){
builder.append(',');
}
}
or just use apache commons-lang StringUtils.join()
或者只使用 apache commons-lang StringUtils.join()
回答by S.Lott
Explicit loops always work better than implicit ones.
显式循环总是比隐式循环更好。
builder.append( "" + array[0] );
for( int i = 1; i != array.length; i += 1 ) {
builder.append( ", " + array[i] );
}
You should wrap the whole thing in an if-statement just in case you're dealing with a zero-length array.
您应该将整个内容包装在 if 语句中,以防万一您正在处理零长度数组。
回答by Jon Skeet
Another alternative is to append the comma before you append i, just not on the firstiteration. (Please don't use "" + i
, by the way - you don't really want concatenation here, and StringBuilder has a perfectly good append(int) overload.)
另一种选择是在附加 i 之前附加逗号,而不是在第一次迭代中。("" + i
顺便说一下,请不要使用- 你真的不想在这里连接,而且 StringBuilder 有一个非常好的 append(int) 重载。)
int[] array = {1, 2, 3...};
StringBuilder builder = new StringBuilder();
for (int i : array) {
if (builder.length() != 0) {
builder.append(",");
}
builder.append(i);
}
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.)
这样做的好处是它可以与任何Iterable
东西一起使用——你不能总是索引事物。(当您真正使用 StringBuilder 时,“添加逗号然后在末尾删除它”是一个不错的建议 - 但它不适用于写入流之类的事情。不过,这可能是解决这个确切问题的最佳方法。 )
回答by Brian
Another approach is to have the length of the array (if available) stored in a separate variable (more efficient than re-checking the length each time). You can then compare your index to that length to determine whether or not to add the final comma.
另一种方法是将数组的长度(如果可用)存储在一个单独的变量中(比每次重新检查长度更有效)。然后,您可以将索引与该长度进行比较,以确定是否添加最后一个逗号。
EDIT: Another consideration is weighing the performance cost of removing a final character (which may cause a string copy) against having a conditional be checked in each iteration.
编辑:另一个考虑是权衡删除最终字符(可能导致字符串复制)的性能成本与在每次迭代中检查条件的性能成本。
回答by FallenAvatar
Here is a solution:
这是一个解决方案:
int[] array = {1, 2, 3...};
StringBuilder builder = new StringBuilder();
bool firstiteration=true;
for(int i : array)
{
if(!firstiteration)
builder.append(",");
builder.append("" + i);
firstiteration=false;
}
Look for the first iteration :)
寻找第一次迭代:)
回答by Paul Brinkley
Two alternate paths here:
这里有两条备用路径:
1: Apache Commons String Utils
2: Keep a boolean called first
, set to true. In each iteration, if first
is false, append your comma; after that, set first
to false.
2:保持一个名为 的布尔值first
,设置为true。在每次迭代中,如果first
为假,则附加您的逗号;之后,设置first
为false。
回答by Omar Kooheji
Maybe you are using the wrong tool for the Job.
也许您在作业中使用了错误的工具。
This is more manual than what you are doing but it's in a way more elegant if not a bit "old school"
这比你正在做的更手动,但它在某种程度上更优雅,如果不是有点“老派”
StringBuffer buffer = new StringBuffer();
Iterator iter = s.iterator();
while (iter.hasNext()) {
buffer.append(iter.next());
if (iter.hasNext()) {
buffer.append(delimiter);
}
}
回答by bruno conde
Another solution (perhaps the most efficient)
另一种解决方案(也许是最有效的)
int[] array = {1, 2, 3};
StringBuilder builder = new StringBuilder();
if (array.length != 0) {
builder.append(array[0]);
for (int i = 1; i < array.length; i++ )
{
builder.append(",");
builder.append(array[i]);
}
}