** Table of Contents ** If you're using a modern language, it's a pattern you wouldn't bother to implement.
But are you going to follow in the footsteps of our predecessors when there was no such module in the standard library? I will implement it with.
Provides a way to access the elements of an aggregate object in sequence without exposing the underlying internal representation.
(If you define List firmly, it will be expressed like this ...)
-Abstract class for accessing Iterator elements in order ・ Concrete class of ConcreteIterator Iterator class -Abstract class for creating an instance of Aggregate Iterator type -Concrete Aggregate Aggregate class concrete class
Let's implement something like Java's Iterator. What implementation and when should ** Aggregate ** and ** Concrete Aggregate ** be used? I think that it is unnecessary if Iterator is implemented in the generic type.
Iterator.kt
package iterator
interface Iterator<T> {
    var index: Int
    var list: ArrayList<T>
    /**
     *Get the indexth element
     */
    fun elementAt(index: Int): T
    /**
     *Check if there are still elements left
     */
    fun hasNext(): Boolean
    /**
     *Get the next element
     */
    fun next(): T
    /**
     *Add an element
     */
    fun add(element: T)
    /**
     *Delete the indexth element
     */
    fun remove(index: Int)
}
ConcreteIterator.kt
package iterator
class ConcreteIterator<T>(vararg elements: T): Iterator<T> {
    override var index = 0
    override var list = ArrayList<T>()
    init {
        list.addAll(elements)
    }
    override fun elementAt(index: Int): T {
        return list[index]
    }
    override fun hasNext(): Boolean {
        return index != list.size
    }
    override fun next(): T {
        return list[index++]
    }
    override fun add(element: T) {
        list.add(element)
    }
    override fun remove(index: Int) {
        list.removeAt(index)
    }
}s
Client.kt
package iterator
class Client {
    init {
        val strIterator = makeStrIterator()
        while(strIterator.hasNext()) {
            println(strIterator.next())
        }
        val intIterator = makeIntIterator()
        while (intIterator.hasNext()) {
            println(intIterator.next())
        }
    }
    private fun makeStrIterator(): Iterator<String> {
        val iterator = ConcreteIterator("Ichi", "To", "Mr.")
        iterator.add("Yon")
        return iterator
    }
    private fun makeIntIterator(): Iterator<Int> {
        return ConcreteIterator(1, 2, 3)
    }
}
[out-put]
Ichi
To
Mr.
Yon
1
2
3
With the above, I was able to know the hardships of my predecessors.
Recommended Posts