[Java] Iterator: Iterable & Iterator

The iterator in our Java is an interface called Iterator. It has two abstract methods

hasNext method: used to determine whether there is data access.

next method: used to access the next data of the collection.

Iterators can access collection data of different characteristics without caring about their internal implementation.

Notice:

The collection does not directly implement the Iterator interface, but implements the Iterable interface, and uses the method defined by the Iterable interface to return the iterator of the current collection.

Among them, collection inherits the Iterable interface, so all collections in the collection system must return iterators in this way.

What are the benefits of doing this?

Because if the collection directly implements the iterator, then others call the next() interface of the current collection, which will affect your traversal of data.

You originally hoped to traverse the data from scratch, but maybe someone else has already traversed the data, and you will not get the data at all.

By implementing Iterable, a new iterator can be returned each time, and different iterators will not affect each other when traversing data. Here it can be seen that the iterator is independent and isolated.

Let's imagine, if we are traversing with the iterator, what if the collection is adding or deleting data? Will the difference affect the traversal of the iterator? The Java standard library handles this situation. Expand here later.

When we use the iterator again, we can directly use the for-each loop to implement the iterator. In fact, the for-each loop is a syntactic sugar of Java. After decompilation, we can find that it uses an iterator.

Guess you like

Origin blog.csdn.net/weixin_43918614/article/details/124462312