The iterable and iterator of Java.util

Source: Internet
Author: User
Tags iterable

Package Java.lang;
Import Java.util.Iterator;

Public interface Iterable<t> {

Iterator<t> Iterator ();
}

Iterable is located in the Java.lang package, which holds a iterator reference

Package java.util;

Public interface Iterator<e> {
Boolean hasnext ();

E next ();

void Remove ();
}

Iterator is also an interface that contains three methods, Hasnext, Next, remove

 Public Interface extends iterable<e> {}

Java.util.Collection inherits from Java.lang.Iterable, why does the JDK author design This, why does the collection interface not inherit directly from iterator?

In fact, this is also a design pattern: iterator design mode

Why this design, if collection directly from the iterator inheritance, then the collection implementation class must be directly implemented Hasnext, next, remove method.

1. This can lead to code confusion, the iterative code is confused with the implementation code of the collection itself, resulting in reading difficulties, and there are methods to repeat, such as remove, can not be separated from the implementation of the iteration

2. The current cursor pointer must be included in the collection implementation class, and processing is quite awkward when concurrency

3. The interface is not unified, collection inherit from the Iterable, in the iteration only need to get its iterator (internal class implementation), with a unified object iteration, and multiple iterators can do non-interference

The iterable and iterator of Java.util

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.