preface

Welcome to pay attention to the public number: Coder programming to obtain the latest original technical articles and related free learning materials, anytime, anywhere to learn technical knowledge!

In the previous article through interview questions, let us understand the Collection, we will find that there is an interface above the Collection interface Iterable, inside the Iterable interface and the Iterator interface, then what is the difference between them? Iterable: Iterator: Iterator: Iterator: Iterator: Iterator: Iterator: Iterator: Iterator: Iterator Let’s get started

Questions related to:

  • 1. Say Iterable?
  • 2. The Iterable structure?
  • 3. What about Iterator?
  • 4. The Iterator structure?
  • 5. What is the difference between forEachRemaining() and forEach()?
  • 6. How to use Iterator?
  • 7. What is the difference between Iterable and Iterator?

As you can see from the interview questions above, they are all the same, just a different way of asking questions. As long as we can grasp the core points, we can easily handle any question the interviewer asks us!

Source BCO:

Iterable: Iterable; Iterable: Iterable; Iterable: Iterable; Repeatable; The iteration; So we know that the collection object that implements this interface supports iteration and is iterable.

Iterator: Iterator is an Iterator. It is an object that provides the mechanism for iterating. From UML diagrams, we can also see that the Iterable interface is the top-level interface of the Java Collections framework, implementing this interface to allow collection objects to iterate over their elements through iterators. There is also a Java design pattern called the Iterator pattern. Iterator is one of the best examples of the Iterator pattern.

1. Say Iterable?

Iterable has three methods, respectively

  • Iterator iterator();
  • default void forEach(Consumer
    action){}; Added after JDK 1.8
  • default Spliterator spliterator(){}; Added after JDK 1.8

So let’s talk a little bit about how this works.

1.1 Iterator () methods in the Iterable interface

Iterator<T> iterator();

Copy the code

This interface essentially returns an iterator on an element of type T. More on Iterator below.

1.2 forEach() in Iterable

default void forEach(Consumer<? Super T> action) {// Verify that the action is null. If the action is null, throw NullPointerException objects.requirenonNULL (action);for(T t : this) { action.accept(t); }}Copy the code

This method is a looping output that iterates through the internal elements and performs the specified operations on the elements. Such as:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
 numbers.forEach(integer -> System.out.println(integer));
Copy the code

Performing the given action on each element of this Iterable directs all elements to be processed or until the action throws an exception. Unless specified by the implementation class, actions are executed in the order of iteration (if an iteration order is specified). Exceptions thrown by the action are passed to the caller

1.3 Spliterator () in the Iterable interface

default Spliterator<T> spliterator() {
    return Spliterators.spliteratorUnknownSize(iterator(), 0);
}
Copy the code

This method provides an iterator that can walk through elements in parallel to meet the requirements of the modern CPU multi-core era. Create a Spliterator on the elements described by the Iterable interface. The default implementation creates an early-bound spliterator from iterable’s Iterator. This spliterator inherits the fail-fast properties of iterable’s iterator. The default implementation should always be overridden. The spliterator returned by the default implementation has poor shredability, is not customized to the specified size, and does not report any spliterator properties. Implementation classes almost always provide better implementations.

2. What about Iterator?

2.1 What is Iterator?

Iterator is called a sequential traversal Iterator, and the JDK implements data structures in the collection framework by default. One of the nice things about Iterator in practice is that you can delete elements by iterating through them. I’ll illustrate this later with the Iterator() method in the ArrayList.

2.2 Iterator?

The source diagram Iterator interface defines four methods, respectively

  • Boolean hasNext() : Returns True if the iterated collection has not yet been iterated
  • Object Next () : Returns the next element in the collection
  • Remove () : Removes the element from the collection that was last returned by the next() method
  • Void forEachRemaining(Consumer Action) : The default method added since JDK 1.8 uses Lambda expressions to iterate over collection elements

2.3 forEachRemaining() in Iterator

A default method added to Iterator after JDK1.8

List<String> arr=new ArrayList<>(); arr.add("hello");
arr.add(("world"));
arr.iterator().forEachRemaining(str-> System.out.println(str));
Copy the code

2.3.1 What is the difference between forEachRemaining() and forEach()?

ForEachRemaining () the source code:

default void forEachRemaining(Consumer<? super E> action) {
    Objects.requireNonNull(action);
    while (hasNext())
        action.accept(next());
}
Copy the code

The forEach () the source code:

default void forEach(Consumer<? super T> action) {
    Objects.requireNonNull(action);
    for(T t : this) { action.accept(t); }}Copy the code

Through the source code, we can see the difference between them and the connection. Similarities:

  • I can walk through the set
  • Are the default methods of the interface
  • Both were introduced in version 1.8

The difference between:

  • Inside the forEachRemaining() method is an Iterator that iterates all the elements, and inside the forEach() method is an enhanced for loop.
  • The forEach() method can be called multiple times, and the second call to forEachRemaining() does nothing because there is no next element.

3. How to use Iterator?

Just a quick example of a chestnut

List list = new ArrayList();
list.add("Public Account");
list.add("Coder programming");
for(Iterator iter = list.iterator(); iter.hasNext();) { String str = (String)iter.next(); System.out.println(str); } /* The iterator is used forwhileIterator iter = list.iterator();while(iter.hasNext()){ String str = (String) iter.next(); System.out.println(str); } * /Copy the code

Recommended reading

  • Let you know about Collection knowledge!

  • Let you understand the difference between process and thread and contact!

At the end of the article

Iterable: Iterator: Iterator: Iterator: Iterator: Iterator: Iterator: Iterator: Iterator: Iterator: Iterator Welcome to pay attention to the public number: Coder programming to obtain the latest original technical articles and related free learning materials, anytime, anywhere to learn technical knowledge!

  • Github home page directory

  • Gitee personal home page directory

Welcome to follow and Star~