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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With