My Java implementation and some thoughts about what an iterator should look like


  • 1
    E

    My implementation is as follows:

    public class Vector2D implements Iterator<Integer> {
    
        private final Iterator<List<Integer>> listIterator;
        private Iterator<Integer> sublistIterator;
        
        public Vector2D(List<List<Integer>> vec2d) {
            listIterator = vec2d.iterator();
            advanceListIterator();
        }
    
        private void advanceListIterator() {
            while (listIterator.hasNext()) {
                sublistIterator = listIterator.next().iterator();
                if (sublistIterator.hasNext()) {
                    break;
                }
            }
        }
        
        @Override
        public Integer next() {
            if (!hasNext()) {
                throw new java.util.NoSuchElementException();
            }
            Integer ret = sublistIterator.next();
            if (!sublistIterator.hasNext()) {
                advanceListIterator();
            }
            return ret;
        }
    
        @Override
        public boolean hasNext() {
            return sublistIterator != null && sublistIterator.hasNext();
        }
    }
    

    The idea is no difference from most of the others -- just use one iterator on the outer list, and one on the inner list. I'd like to share my implementation here because most of the implementations I saw have some flaws.
    Personally I think an ideal iterator should have the following properties:

    1. It should not contain a copy of the original data.
    2. It has a hasNext() method to check if there is more element to be iterated.
    3. It has a next() method to return the next element. If there is no next element, the correct behavior is to throw NoSuchElementException. And this must be done when the iterator class implements Java Iterator interface. Many people have overlooked this in their code. Also next() should always return a valid next element when there is one, even if it is called without hasNext() before it.

Log in to reply
 

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