Is "implements Iterator<Integer>" really necessary?


  • 0
    Z

    I don't think "implements Iterator<Integer>" is necessary.
    The code below passes.

    class PeekingIterator {
    private Integer peekNext = null;
    private Iterator<Integer> iter = null; 
    
    public PeekingIterator(Iterator<Integer> iterator) {
        // initialize any member here.
        iter = iterator;
        if (iter.hasNext()) {
            peekNext = iter.next();
        }
    }
    
    // Returns the next element in the iteration without advancing the iterator.
    public Integer peek() {
        return peekNext;
    }
    
    // hasNext() and next() should behave the same as in the Iterator interface.
    // Override them if needed.
    public Integer next() {
        int returnInt = peekNext;
        peekNext = iter.hasNext() ? iter.next() : null;
        return returnInt;
    }
    
    public boolean hasNext() {
        return peekNext != null;
    }
    

    }


  • 0
    T
    This post is deleted!

  • 1
    T

    The point of the excercise is to create a wrapper around an existing iterator implementation. If you don't implement that interface your class won't be usable in place of the original iterator. Of course for testing it doesn't matter, but if you were to use IRL it might. Most likely the test harness was written without using Iterator<Integer> so that peek() can be called on the object.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.