Sobes.tech
Intern

What is an iterator?

sobes.tech AI

Answer from AI

An iterator is an object that provides a way to sequentially access all elements of a collection without needing to know its internal structure.

Main methods of an iterator in Java:

  • hasNext(): Checks if there are more elements to iterate.
  • next(): Returns the next element in the collection and advances the pointer.
  • remove(): Removes the last element returned by next(). (OptionalOperationException may be thrown if not supported).

Example usage in Kotlin:

fun iterateList(list: List<String>) {
    val iterator = list.iterator()
    while (iterator.hasNext()) {
        val element = iterator.next()
        println(element)
    }
}

Advantages of using an iterator:

  • Abstraction: Hides the internal implementation of the collection.
  • Uniformity: Provides a standard way to traverse different types of collections.
  • Safety: Allows safe removal of elements during iteration using remove().