简体   繁体   中英

Why do for-each loops work for arrays? (Java)

I don't understand how a for each loop can iterate through an Array in Java. My understanding is that for each loops can iterate though any class that implements the Iterable interface, but Arrays in Java don't implement Iterable, so how is it possible a for each loop can be used on them?

If the right-hand side of the for (:) idiom is an array rather than an Iterable object, the internal code uses an int index counter and checks against array.length instead. That's why it can be used to loop through arrays. See the Java Language Specification for further details.

Part of this answer was exempted from here . You can take a look at that question too.

I would like to add, if you want you can easily convert java array to Iterable :

Integer arr[] = { 1, 2, 3, 4, 5};

List<Integer> list = Arrays.asList(arr);
// or
Iterable<Integer> iterable = Arrays.asList(arr);

As per JLS :

The enhanced for statement has the form:

EnhancedForStatement: for ( {VariableModifier} UnannType VariableDeclaratorId: Expression ) Statement

EnhancedForStatementNoShortIf: for ( {VariableModifier} UnannType VariableDeclaratorId: Expression ) StatementNoShortIf

Java foreach loop or enhanced for statement is translated into a basic for statement, as follows:

  1. If the type of Expression is a subtype of Iterable<X> for some type argument X, then let I be the type java.util.Iterator<X>; otherwise, let I be the raw type java.util.Iterator.

The enhanced for statement is equivalent to a basic for statement of the form:

for (I #i = Expression.iterator(); #i.hasNext(); ) {
    {VariableModifier} TargetType Identifier =
        (TargetType) #i.next();
    Statement
}
  1. Otherwise, the Expression necessarily has an array type, T[] .

The enhanced for statement is equivalent to a basic for statement of the form:

T[] #a = Expression;
L1: L2: ... Lm:
for (int #i = 0; #i < #a.length; #i++) {
    {VariableModifier} TargetType Identifier = #a[#i];
    Statement
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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