Next/hasNext use peek


  • 2

    Just a variation where next and hasNext use peek.

    class PeekingIterator implements Iterator<Integer> {
    
    	public PeekingIterator(Iterator<Integer> iterator) {
    	    this.iterator = iterator;
    	}
    
    	public Integer peek() {
    	    if (cache == null && iterator.hasNext())
    	        cache = iterator.next();
            return cache;
    	}
    
    	public Integer next() {
    	    Integer tmp = peek();
    	    cache = null;
    	    return tmp;
    	}
    
    	public boolean hasNext() {
    	    return peek() != null;
    	}
    	
    	private Iterator<Integer> iterator;
    	private Integer cache;
    }

  • 0
    H

    I'm really confused now... I understand the logic of each section is right. But how it works? For example, if call peek() and it will check if iterator .hasNext(), but hasNext() needs to call peek()... to me there's no end. Do you know where I misunderstood?


  • 0

    My own iterator's hasNext is not the same as the source iterator's hasNext.


  • 0
    A

    @StefanPochmann I see. This only works for languages that feature "null != 0"


  • 0
    P

    @StefanPochmann How does the compiler identify which hasNext() to call?


  • 0
    2

    @ParinSanghavi iirc, for Java, it'll default to the children's function first unless you specify super.hasNext()


Log in to reply
 

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