Sitemap
Acing the Software Engineer Interview

A collection of interview prep notes

Member-only story

Iterators

--

Photo by Taylor Brandon on Unsplash

Read full story for free if you don’t have medium membership: https://medium.com/acing-the-software-engineer-interview/iterators-4742a60e584d?sk=6d78f50ff05c99ab2bd19e64d6f19e22

We use them in loops. For example, for(int num: nums) in java.

It is helpful in abstraction as the caller does not need to know the underlying data structure.

There are two commonly used methods

  1. next() -> Moves to the next element. Note that this is an irreversible operation and changes the internal state of the iterator permanently. We are not able to go back in reverse.
  2. hasNext() -> Check if there is a next element to go to.

Properties

  1. Only need to know how to get the next element, and we do not need to store the entire data in memory.
    Imagine it as iterating a Linked list, where we keep moving from head to the end. As items are consumed, they are discarded and the next element is replaced with it.
  2. Can use it to represent sequences without incurring memory, O(1). For example, if we want to iterate through a range of values.
  3. Support infinite data.
public class RangeIterator {
private final int max;
private int current;

public RangeIterator(int min, int max) {
this.current = min…

--

--

LiveRunGrow
LiveRunGrow

Written by LiveRunGrow

𓆉︎ 𝙳𝚛𝚎𝚊𝚖𝚎𝚛 🪴𝙲𝚛𝚎𝚊𝚝𝚘𝚛 👩‍💻𝚂𝚘𝚏𝚝𝚠𝚊𝚛𝚎 𝚎𝚗𝚐𝚒𝚗𝚎𝚎𝚛 ☻ I write & reflect about software engineering, my life and books. Ŧ๏ɭɭ๏ฬ ๓є!

No responses yet