Java ternary operator makes it conciser to 6-Line


  • -1
    L
    class PeekingIterator implements Iterator<Integer> {
        private Integer cache = null;
        private Iterator<Integer> it;
    	public PeekingIterator(Iterator<Integer> iterator) { it = iterator; }
    	public Integer peek() {
    	    return cache == null ? (cache = it.next()) : cache;
    	}
    	@Override
        public Integer next() {
            return cache == null ? it.next() : new Integer(cache.intValue() + ((cache = null) == null ? 0 : 0));
        }
    	@Override
    	public boolean hasNext() {
    	    return cache != null || it.hasNext();
    	}
    }

  • 0

    Nice peek and nice name cache, but next can be a lot simpler. There's no need to create a new Integer object and you don't need to check for null twice...


  • 0
    L

    Stephan, thanks for checking. I tried but only below works, and it makes it not generics.

    public Integer next() {
        return cache == null ? it.next() : new Integer(cache.intValue() + ((cache = null) == null ? 0 : 0));
    }

  • 0

    Ha, sorry, apparently I was unclear. I didn't mean any such trickery. I just meant this, a simpler version of your original:

    public Integer next() {
        Integer tmp = cache != null ? cache : it.next();
        cache = null;
        return tmp;
    }
    

  • 0
    L

    This was my first refractory this morning. ☺


Log in to reply
 

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