inderjeet singh
inderjeet singh

Reputation: 23

Java Collections hasnext() and next() method

Iterator is a interface in java and this interface has two main methods hasNext() and next().

As we know Iterator is a interface and it can't implement these two methods. so i want to know in which class java implemented these two methods.

We using these method for iterate over list, set and other collection so somehow these methods were implemented. Please suggest me the class names which implemented above two methods.

Upvotes: 0

Views: 1906

Answers (2)

dkatzel
dkatzel

Reputation: 31648

Most of the Collection classes use private inner classes for their Iterator implementations that use implementation specific knowledge to iterate more efficiently.

For example here is java.util.ArrayList Iterator implementation from Java 6

Note that it is not a static inner class so it can reference private fields (modCount) in the ArrayList to check for ConcurrentModificationExceptions

 /**
 * An optimized version of AbstractList.Itr
 */
private class Itr implements Iterator<E> {
    int cursor;       // index of next element to return
    int lastRet = -1; // index of last element returned; -1 if no such
    int expectedModCount = modCount;

    public boolean hasNext() {
        return cursor != size;
    }

    @SuppressWarnings("unchecked")
    public E next() {
        checkForComodification();
        int i = cursor;
        if (i >= size)
            throw new NoSuchElementException();
        Object[] elementData = ArrayList.this.elementData;
        if (i >= elementData.length)
            throw new ConcurrentModificationException();
        cursor = i + 1;
        return (E) elementData[lastRet = i];
    }

    public void remove() {
        if (lastRet < 0)
            throw new IllegalStateException();
        checkForComodification();

        try {
            ArrayList.this.remove(lastRet);
            cursor = lastRet;
            lastRet = -1;
            expectedModCount = modCount;
        } catch (IndexOutOfBoundsException ex) {
            throw new ConcurrentModificationException();
        }
    }

    final void checkForComodification() {
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
    }
.... etc


}

Upvotes: 0

Erik Gillespie
Erik Gillespie

Reputation: 3959

The JavaDoc for Iterator provides a list of implementing classes.

Start there and then click your way into those and you can discover a variety of implementations of the Iterator interface.

IDEs typically offer a feature that lets you view all interfaces that extend or classes that implement a given interface.

Upvotes: 0

Related Questions