[JAVA] Iterator implementation (eg Fibonacci sequence)

Java extension for statement is very convenient I learned that my own class is also given as an iterator, so my memo (I think there weren't many articles because it was too basic ....)

How to use

Main.java


package fibonacci;

class Main{
  public static void main(String[] args){
    for(int i:Fibonacci.to(10)){
      System.out.println(i);
    }
  }
}

Explanation of extended for statement for (definition of a variable that stores the value returned by the iterator: iterator)

Now the actual implementation of the Fibonacci class

Fibonacci.java


package fibonacci;

import java.util.Iterator;

public class Fibonacci implements Iterator<Integer>, Iterable<Integer>{
	private int num1;
	private int num2;
	private int num3;
	private int count;
	private int to;
	
	public Fibonacci(int to){
		this.num1 = 0;
		this.num2 = 1;
		this.to = to;
		this.count = -1;
		
	}
	
	public static Iterable<Integer> to(int num){
		return new Fibonacci(num);
		
	}
	
	@Override
	public Iterator<Integer> iterator(){
		return this;
	}
	
	@Override
	public boolean hasNext(){
		if(count < to){
			count++;
			return true;
		}
		return false;
	}
	
	
	@Override
	public Integer next(){
		if(count < 2){
			return count;
		}

		num3 = num1 + num2;
		remove();
		
		return num3;
	}
}

First of all, the interface that is implemented Iterable and Iterator interfaces

I wrote earlier that an iterator is specified after the: (colon) in the extended for statement, but it seems a little different. To be able to use it in an extended for statement, it must be a class that implements the Iterable interface.

The iterator method of the Iterable interface returns an object of Iterator , so it feels like looping the values that it returns one by one in the for statement.

The methods that need to be implemented in the Iterator interface boolean hasNext() T next()

For the time being, if you implement these, you can turn it with for. Both are as the name implies. boolean hasNext () is a method that determines "whether or not there is a next value" T next () is a method that returns the next value of type T

When a class that implements Iterable is specified in the extension for, first The method that returns Iterator (to (int num) in this case) is called. It feels like T next () is executed when boolean hasNext () returns true.

Another thing I was interested in was the void remove () and void forEachRemaining (Consumer <? Super E> action) methods. Since both have a default clause, no error will occur even if you do not implement it, and this case is not a problem. (If you understand it, please let me know)

Execution example

% java Main
0
1
1
2
3
5
8
13
21
34
55

Recommended Posts

Iterator implementation (eg Fibonacci sequence)
Fibonacci sequence with (memoization) recursive function