1. 程式人生 > >JAVA-for each用法

JAVA-for each用法

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 官方連結

                        希望文章對你有幫助!