Test cases should include collections containing *null*


  • 2
    J

    Some java collections, such as ArrayList, are allowed to contain null elements. Any implementation of Iterator needs to consider this.

    The test cases should check that the iterator handles collections containing null, such as:
    [1,2,3,null,4,5,6]

    The test cases should also check that the peek() and next() method throw java.util.NoSuchElementException when there is no next element.

    The current set of test cases allows solutions like this:

    //*****************
    // INCORRECT
    //*****************
    class PeekingIterator implements Iterator<Integer> {
    
        final Iterator<Integer> iterator;
        
        Integer next = null;
        
    	public PeekingIterator(Iterator<Integer> iterator) {
    	    this.iterator = iterator;
    	    if(iterator.hasNext()){
    	        next = iterator.next();
    	    }
    	}
    
    	public Integer peek() {
            return next;
    	}
    
    	@Override
    	public Integer next() {
    	    Integer result = this.next;
    	    if(iterator.hasNext()){
    	        next = iterator.next();
    	    }else{
    	        next = null;
    	    }
    	    return result;
    	}
    
    	@Override
    	public boolean hasNext() {
    	    return next != null;
    	}
    }
    

    The following is a correct implementation of Iterator:

    //*****************
    // CORRECT
    //*****************
    class PeekingIterator implements Iterator<Integer> {
    
        final Iterator<Integer> iterator;
        
        Integer next = null;
        
        boolean hasNext = false;
    
    	public PeekingIterator(Iterator<Integer> iterator) {
    	    this.iterator = iterator;
    	    if(hasNext = iterator.hasNext()){
    	        next = iterator.next();
    	    }
    	}
    
        public Integer peek() {
            if(!hasNext) throw new java.util.NoSuchElementException();
            return next;
    	}
    
    	@Override
    	public Integer next() {
    	    if(!hasNext) throw new java.util.NoSuchElementException();
    	    Integer result = next;
    	    if(hasNext = iterator.hasNext()){
    	        next = iterator.next();
    	    }
    	    return result;
    	}
    
    	@Override
    	public boolean hasNext() {
    	    return hasNext;
    	}
    }

Log in to reply
 

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