Iterable and Iterator of java. util, java. utiliterable

Source: Internet
Author: User

Iterable and Iterator of java. util, java. utiliterable

package java.lang;
import java.util.Iterator;

public interface Iterable<T> {

Iterator<T> iterator();
}

Iterable is located in the java. lang Package, which holds an 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, and remove.

public interface Collection<E> extends Iterable<E> {}

Java. util. Collection inherits from java. lang. Iterable. Why is the jdk author designed this way? Why is the Collection interface not inherited directly from Iterator?

In fact, this is also a design model: Iterator Design Model

If the Collection is directly inherited from the Iterator, the Collection implementation class must directly implement the hasNext, next, and remove methods.

1. This will cause code confusion. The iterative code and the Collection implementation code are mixed together, making reading difficult and there are repeated methods. For example, removing can not separate iteration from itself.

2. The current cursor pointer must be included in the Collection implementation class, which is quite embarrassing for concurrent processing.

3. the access interfaces are not uniform. If Collection inherits from Iterable, you only need to get its Iterator (internal class implementation) during iteration, and use unified object iteration, and multiple iterators can do not interfere with each other.

 

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.