Java for( x : y) 执行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6216275/
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
Java for( x : y) execution
提问by Rand
I have the following for loop:
我有以下 for 循环:
for(String s : someString.split("\s+")){
//do something
}
Does java execute the split() method each time the loop iterates, or does it do it only once and keep a temp array to iterate on?
java 是在每次循环迭代时执行 split() 方法,还是只执行一次并保留一个临时数组进行迭代?
回答by RMT
回答by Peter Lawrey
It stores the array in a temporary variable before using it.
在使用数组之前,它将数组存储在一个临时变量中。
回答by bmscomp
No the split is executed once on the string and after that the loop iterate over the result
不分割在字符串上执行一次,然后循环迭代结果
回答by James P.
The split method is only called once. Think of the structure (also known as a for-each) as follows:
split 方法只被调用一次。将结构(也称为 for-each)考虑如下:
- The second argument is evaluated and kept for the duration of the loop.
- If the argument gives an Iterable or is an array (special case), a check is then made to see if the type of the first argument corresponds with the elements that are returned.
- The process enters the loop and executes the code inside the scope and exits when there are no more elements left.
- 评估第二个参数并在循环期间保留。
- 如果参数给出一个 Iterable 或者是一个数组(特殊情况),然后检查第一个参数的类型是否与返回的元素对应。
- 进程进入循环并执行作用域内的代码,当没有更多元素时退出。
More information can be had here: http://www.leepoint.net/notes-java/flow/loops/foreach.html
更多信息可以在这里获得:http: //www.leepoint.net/notes-java/flow/loops/foreach.html
P.S: This works with Java 5 minimum.
PS:这至少适用于 Java 5。