lasan
lasan

Reputation: 365

How is the for loop iterating to the next item in below code

I'm trying to learn the Iterator design pattern in Java. Below is a code sample of the implementation of the iterator pattern.

public class IteratorDemo {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
       NameRepository repo=new NameRepository();

       for(Iterator iter=repo.getIterarter(); iter.hasNext();){

           String name=(String) iter.next();

           System.out.println("Name : "+name);
       }


    }

}

interface Container{
    public Iterator getIterarter();
}

interface Iterator{
    public boolean hasNext();
    public Object next();
}



class NameRepository implements Container{
    private String[] names={"A","B","C","D","E","F"};

    @Override
    public Iterator getIterarter() {
        return new NameIterator();
    }

    private class NameIterator implements Iterator{

    int index;
    @Override
    public boolean hasNext() {
        return index < names.length;

    }

    @Override
    public Object next() {
        if(this.hasNext()){
            return names[index++];
        }
        return null;
    }

}
}

Here the output is A , B, C, D,E ,F. My question is how this for loop iterates to the next item ? As it seems there is no iterating value in the code, but still it prints out the whole array

Upvotes: 0

Views: 70

Answers (1)

Umesh Kumar Sharma
Umesh Kumar Sharma

Reputation: 306

See, index is increasing every time if index < names.length **

@Override
    public Object next() {
        if(this.hasNext()){
            return names[index++];
        }
        return null;
    }

**

Upvotes: 1

Related Questions