-1

I know an enhanced for-loop (since java 1.5) can be used to iterate over collections of class-types that implement the Iterator interface. It can however also be used to iterate over arrays of primitive types e.g. int, boolean,... So my logical conclusion was that thanks to autoboxing and unboxing, for example, primitve integers were being wrapped inside their reference-type which would then on their turn, implement Iteratable.

However, when I looked up the documentation of java.lang.Integer, nowhere is mentioned any extension or implementation of a superclass or interface that could implement or extend the Iterable interface. How does an enhanced for-loop know how to loop over primitive types without the Iterable interface being implemented?

shmosel
  • 49,289
  • 6
  • 73
  • 138
Programmer1994
  • 955
  • 3
  • 13
  • 29
  • 1
    At least related: http://stackoverflow.com/questions/3912765/how-does-the-enhanced-for-statment-work-for-arrays-and-how-to-get-an-iterator-f, http://stackoverflow.com/questions/85190/how-does-the-java-for-each-loop-work?rq=1 – T.J. Crowder Aug 29 '16 at 16:44

1 Answers1

6

You're looking in the wrong place. It's not the entries that would need to be iterable, it's the array that would need to be. But the real answer is that the enhanced for loop has native support for looping through arrays. E.g., it's for looping through arrays and, separately, iterables. Seel JLS§14.14.2 - The enhanced for statement, which gives two possible uses:

  • If the type of Expression is a subtype of Iterable, then the translation is as follows.

    (...specifies algorithm for looping through Iterable...)

  • Otherwise, the Expression necessarily has an array type, T[].

    (...specifies algorithm for looping through T[] array...)

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875