简体   繁体   English

用于(x:y)执行的Java

[英]Java for( x : y) execution

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()方法,还是只执行一次并保持临时数组迭代?

It only does it once, and uses that array and interates through it. 它只执行一次,并使用该数组并通过它进行交互。

Edit: from Mat This is the reference 编辑:来自Mat这是参考

它在使用之前将数组存储在临时变量中。

在字符串上不执行拆分一次,然后循环遍历结果

The split method is only called once. split方法只调用一次。 Think of the structure (also known as a for-each) as follows: 考虑结构(也称为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. 如果参数给出Iterable或者是数组(特殊情况),则进行检查以查看第一个参数的类型是否与返回的元素相对应。
  • The process enters the loop and executes the code inside the scope and exits when there are no more elements left. 进程进入循环并执行范围内的代码,并在没有剩余元素时退出。

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

PS: This works with Java 5 minimum. PS:这适用于Java 5最低要求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM