Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 727
timg Avatar asked Sep 18 '26 11:09

timg


1 Answers

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);
like image 190
Plabon Dutta Avatar answered Sep 20 '26 01:09

Plabon Dutta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!