JAVA-for each用法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/UNIONDONG/article/details/85035388

for each 循环

  1. 这是java中功能很强的一种循环方式,可以用来依次处理数组中的每个元素,而不必定义下标值。
  2. 语法格式为:for(variable,collection) statement
    variable,定义一个变量暂存集合中的每一个元素,并执行相应语句。
    collection,这一集合必须是一个数组或者一个实现了Iterable接口的类对象。
    statement,写下语句块,实现的功能。
  3. 官方定义如下:
default void forEach​(Consumer<? super T> action)
Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception. Actions are performed in the order of iteration, if that order is specified. Exceptions thrown by the action are relayed to the caller.
The behavior of this method is unspecified if the action performs side-effects that modify the underlying source of elements, unless an overriding class has specified a concurrent modification policy.

Implementation Requirements:
The default implementation behaves as if:


     for (T t : this)
         action.accept(t);
 
Parameters:
action - The action to be performed for each element
Throws:
NullPointerException - if the specified action is null
Since:
1.8

  1. for each实现的功能完全能被for来替代。

  2. 附上链接: forEach 官方链接

                        希望文章对你有帮助!
    

猜你喜欢

转载自blog.csdn.net/UNIONDONG/article/details/85035388