Reputation: 401
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?
Upvotes: 3
Views: 399
Reputation: 7269
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);
Upvotes: 4
Reputation: 1599
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:
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
}
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
}
Upvotes: 2