All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g0201_0300.s0284_peeking_iterator.PeekingIterator Maven / Gradle / Ivy

There is a newer version: 1.24
Show newest version
package g0201_0300.s0284_peeking_iterator;

// #Medium #Array #Design #Iterator

import java.util.Iterator;

public class PeekingIterator implements Iterator {
    private Iterator it;
    private Integer current;

    public PeekingIterator(Iterator iterator) {
        // initialize any member here.
        it = iterator;
        current = it.next();
    }

    // Returns the next element in the iteration without advancing the iterator.
    public Integer peek() {
        if (current == null) {
            current = it.next();
        }
        return current;
    }

    // hasNext() and next() should behave the same as in the Iterator interface.
    // Override them if needed.
    @Override
    public Integer next() {
        Integer temp = current;
        current = it.hasNext() ? it.next() : null;
        return temp;
    }

    @Override
    public boolean hasNext() {
        return current != null;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy