Why arrays do not implement the Iterable interface, but can use a foreach statement to traverse

Source: Internet
Author: User
Tags iterable

In Java, it's always confusing for an array to be able to use a foreach statement.

For objects that can be traversed with a foreach statement, there are only two cases, one of which is that traversing an object must implement the Iterable interface and implement the Ierator () method, which is the premise of the object using the foreach statement. Another case is a special object array. So how do you understand how to use foreach for arrays?

The first thing to note is that the object that implements the Java.lang.Iterable interface can be traversed with for-each, but it is not necessarily the interface that can be traversed with For-each , such as the special object of an array. However, there is little information on the Internet, but I can only say my own understanding.

I think it is possible for an array object to traverse an element with a foreach statement because the JVM converts the Foreach loop for the array to a circular reference to each of the arrays at the bottom. Similar to converting to a normal for statement at the bottom, we are guaranteed to iterate correctly when using the foreach statement.

Why arrays do not implement the Iterable interface, but can use a foreach statement to traverse

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.