Does Java's for-each call an embedded method (that returns the collection) for every iteration?

前端 未结 4 1138
借酒劲吻你
借酒劲吻你 2021-02-03 20:41

If there is a method call MyClass.returnArray() and I iterate over the array using the for-each construct (also called the \"enhanced for\" loop):

f         


        
4条回答
  •  后悔当初
    2021-02-03 21:09

    No.

    The for loop is just syntactic sugar. It behaves differently depending on whether or not it is applied to an Array argument or an object implementing the Iterable interface.

    For Iterable objects, the loop expands to something like this:

    Iterator iter = iterableObject.iterator();
    while (iter.hasNext()) {
       ArrayElement e = iter.next();
       // do smth
    }
    

    What your example code is actually doing is something like this:

    Object[] temp = Method.returnArray();
    for ( int i = 0; i < temp.length; i++ ) {
      ArrayElement e = (ArrayElement) temp[i];
      // do smth
    }     
    

提交回复
热议问题