Abin Lakhanpal
Abin Lakhanpal

Reputation: 390

What is iterator in java actually?

I have searched in JavaDoc, Iterator in java is interface. But if it is interface then where is the implementation of the hasNext, next , remove methods of iterator interface.

I tried to search in Stackoverflow for this question and i come up with this thread.

Where are Iterator interface methods hasNext(), next(), remove() defined? Because interfaces never define methods only declare

As mentioned in above thread its implementation is hidden But why it is hidden ?

Upvotes: 0

Views: 1319

Answers (3)

Hyperion
Hyperion

Reputation: 382

Interfaces just blueprints. They told just WHAT to do, not HOW. Classes which implements X interface (eg. Iterator) MUST told HOW to do. If you look ArrayList's source code, you'll see implementation of Iterator's methods, like ArrayList.java

Upvotes: 1

nitishagar
nitishagar

Reputation: 9403

From what I understand you implement these method for your data structured to comply with the interface. There are no implementations available for the hasNext(), next() and remove() method as such.

Concrete classes have an implementation of these (default implementation). Like LinkedList traverses in order. For iterating in any other order you can implement the interface. Below is an example to iterate in reverse order:

@Override
public Iterator<Type> iterator() {
    Iterator<Type> it = new Iterator<Type>() {

        private int currentIndex = arrayList.size();

        @Override
        public boolean hasNext() {
            return arrayList[currentIndex] != null;
        }

        @Override
        public Type next() {
            return arrayList[currentIndex--];
        }

        @Override
        public void remove() {
            throw new UnsupportedOperationException();
        }
    };
    return it;
}

Upvotes: 1

Robert Wadowski
Robert Wadowski

Reputation: 1427

That is the idea of interface. Generally in programming the weaker connection you have between objects the better. Only interface is exposed intentionally for collections. It is expected from client to NOT TO KNOW ( or better there is no reason to know ) how implementation of iterator looks like, client expect described behaviour from iterator - check if has next element, get next element. How it is implemented is irrelevant and only that matters to him. The point is that you want use it and you only should know concept of iterator itself.

This is reason why is hidden

Upvotes: 1

Related Questions