The difference between iterator and iterable in Java

Source: Internet
Author: User
Tags iterable

Definition of iterable:

Java.lang Bag

/** * Implementing this interface allows a object to be the target of * the "foreach" statement. * * @param <T> The type of elements returned by the iterator * * @since 1.5 */public interface iterable<t> {
   /**     * Returns An iterator over a set of elements of type T.     *     * @return an Iterator.     *    /iterator<t> Iterator ();}

Definition of iterator:

Java.util Package:

Public interface Iterator<e> {    boolean hasnext ();    E next ();    void Remove ();

Iterator is an iterator class, and iterable is designed to iterate using foreach as long as the interface is implemented.

The iterator interface is encapsulated in iterable, and the iterator iterator can be used as long as the class that implements the Iterable interface is implemented.

Collections collection, List, and set are iterable implementation classes, so they and their subclasses can iterate using foreach.

So why don't these collection classes directly implement iterator?

Iterator and Core methods next (), Hasnext (), remove (), are dependent on the current position, and if these collections are implemented directly iterator, you must include a pointer to the current iteration position. When a collection is passed between methods, the value after next () is not known because the current position is unknown. When implementing iterable, however, each invocation returns an iterator from the beginning, each of which does not affect each other.

The difference between iterator and iterable in Java

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.