Java and Iterator Part 1 External Iterator

I've heard a little about Iterator I was aware that it was a word related to iterative processing. I wasn't sure exactly what it actually meant, so I looked it up.

First ...

Even if I looked up the word Iterator at once, it seemed to be used in multiple meanings, and I was confused at first. As far as the Java context is concerned, it seems to be used mainly in the following two meanings.

** 1. A design pattern defined by the GoF book that provides a way to enumerate container objects ** ** 2. Iterator interface defined in java.util.Iterator **

First of all, there is a design pattern called Iterator * (1), The Iterator interface * (2) incorporates this into the Java language specifications.

Once you can organize this, you will be able to understand from the context which meaning it is used for. Gathering information has become much easier.

What is the Iterator pattern?

According to the wiki it looks like this

By making the means of enumerating the elements of the container object independent The purpose is to provide iterators that do not depend on the internal specifications of the container.

The jargon is difficult ... I didn't really understand what a container was, so I went to the wiki.

A container is a general term for data structures, abstract data types, or classes that represent a collection of objects.

You can read the container as a collection ...? Trying to be good, if you roughly translate the contents of the Iterator pattern of the wiki again

By defining the object type itself such as List, array, MAP, and the iterative processing method separately Regardless of the type of collection, we will be able to iterate in the same way!

Is it like that?

When using an extended for statement or Stream API, we list<string> hogelist = new arraylist<>(); Probably string[] hogelist = new string[2]; It doesn't matter

for (String hoge : hogeList) { System.out.println(hoge); }

I used to hang it in the same way regardless of the mold. This is because the implementation based on the Iterator pattern is actually defined so that you don't have to be aware of it! I mean ...!

Iterator interface

That's why the Iterator interface comes out. At first glance, what is defined in the unconscious place! ?? That is The collection object </ b> implements the Iterator interface </ b>.

As you pointed out in the comments, to be precise By the Iterable interface </ b> implemented by the collection object </ b> You can call the Iterator interface </ b>! It seems.

… If you study alone, you will not notice any misunderstandings and will progress to cancer. I'm really grateful for your suggestions, thank you ...!

The method of the Iterator interface looks like this.

Return type Method Description
boolean hasNext( ) Returns true if the following elements are present in the iterative process.
Object next( ) Returns the next element in the iterative process.
void remove( ) Deletes the last element called in the iterative process.

The Iterable interface looks like this

Return type Method Description
void forEach(Consumer<? super T> action) Performs the action specified for each element of Iterable until all elements are processed or the action throws an exception.
Iterator iterator() Returns an iterator for an element of type T.
Spliterator spliterator() Create a Spliterator for the elements described by this Iterable.

… This is a little interesting because the explanation on the official website is like the explanation for a card game ↓

Implementing this interface allows objects to be targeted in "for-each loop" statements.

for-each loop = extended for statement.

To organize, Collection such as List and MAP defines the nature of the collection. The Iterator interface defines how to iterate You can call the Iterator interface by implementing the Iterable interface in your collection.

Both List and MAP, as long as the collection implements the Iterable interface You can get the Iterator interface Therefore, regardless of the type of collection, if you implement the Iterable interface, you can implement iterative processing.

And I also told you this in the comments Arrays don't implement the Iterable interface ...! I haven't done that, but it seems that Extended for-kun treats only the array specially and interprets it as an ordinary for statement.

Java iteration and Iterator method

HasNext () and remove () when actually using the extension for and StreamAPI I don't remember seeing it, it's just unfamiliar.

It's because Java is doing this and that secretly. Thank you for giving back the crane, I want to look into the other side of the shoji ... and I want to be convinced ... There was a person who decompiled and described the internal processing of the extended FOR statement.

The code posted here is quoted below.

For lists

import java.util.ArrayList;
import java.util.List;
 
public class IteratorSample3 {
    public static void main(String[] args) {
        List list = new ArrayList();
        
        for (int i = 0; i < 10; i++) {
            list.add(new Integer(i));
        }
 
        for (Object o : list) {
            System.out.println((Integer)o);
        }
    }
}

import java.io.PrintStream;
import java.util.*;
 
public class IteratorSample3
{
 
    public IteratorSample3()
    {
    }
 
    public static void main(String args[])
    {
        ArrayList arraylist = new ArrayList();
        for(int i = 0; i < 10; i++)
            arraylist.add(new Integer(i));
 
        Object obj;
        for(Iterator iterator = arraylist.iterator(); 
                                 iterator.hasNext();
                                 System.out.println((Integer)obj))
            obj = iterator.next();
 
    }
}

For arrays

public class IteratorSample5 {
    public static void main(String[] args) {
       int[] numbers = new int[10];
        
        for (int i = 0; i < 10; i++) {
            numbers[i] = i;
        }
 
        for (int i : numbers) {
            System.out.println(i);
        }
    }
}


import java.io.PrintStream;
 
public class IteratorSample5
{
 
    public IteratorSample5()
    {
    }
 
    public static void main(String args[])
    {
        int ai[] = new int[10];
        for(int i = 0; i < 10; i++)
            ai[i] = i;
 
        int ai1[] = ai;
        int j = ai1.length;
        for(int k = 0; k < j; k++)
        {
            int l = ai1[k];
            System.out.println(l);
        }

    }
}

In the case of arrays, access was done using a very ordinary index. It seems that the conversion method is changed by looking at the other party.

If it is a collection object, iterator processing using Iterator If it's an array, the compiler really decides to use a normal for as syntax sugar ...! I couldn't find out if I was on my own. I'm really grateful that someone with exploratory and technical skills will disclose their knowledge ...

There are two Iterator patterns

So far, Java ... or rather, about Iterator patterns and Iterator methods using extended FOR statements. As I was writing, this was actually only half the explanation of the "external iterator" iterator ...!

Recently ... I don't have it at all anymore, but the Stream API that Java8 started to use! It seems that the other half of the iterator, "internal iterator", can be implemented ...!

With that feeling, I'm exhausted, so I'll publish it here. Although it is called an external iterator, the explanation of the extension for is almost the same as it is now, so I will add the extension for later ...

Organize the Japanese language and sentence structure, and if you are lying, correct the content As (2), I will write a summary of studying external iterators in the near future. … It's hard to make it into an article.

  • 8/30… Contents pointed out in the comments and some Japanese corrections *

Keywords to be organized next time

Parallel processing closure Internal iterator

  • Also, I got a comment and learned the name syntax sugar for the first time. I would like to investigate and summarize the difference between syntactic sugar and the arrangement and collection ... *

Reference site

Rethink: GoF Design Pattern Java Iterator (Extended for Syntax) Interface Iterator Java2 SE 5.0 Cheat Sheet Extended for Statement Understanding the basics of Java SE 8 and Stream API

Recommended Posts