Java - Iterator Implementation

> Procedural Languages > Java

1 - About

The iterator implementation in Java is just an inner class that implements the iterator interface.

In order to be able to use it in a for loop construction, the iterable interface must be implemented.

See also: Java - (Enumerable|Iterator) Data Type

Introduced in the Java JDK 1.2 release, the java.util.Iterator interface allows the iteration of container classes. Each Iterator provides a next() and hasNext() method, and may optionally support a remove() method. Iterators are created by the corresponding container class, typically by a method named iterator().

The next() method advances the iterator and returns the value pointed to by the iterator. The first element is obtained upon the first call to next(). To determine when all the elements in the container have been visited the hasNext() test method is used.

3 - Example

package hotitem.data;
 
import java.util.Iterator;
 
/**
 * User: gerard
 * Date: 2/25/14
 * Time: 11:47 AM
 */
public class DataSet implements Iterable<String> {
 
 
    private String myData[] = {"1", "2", "3", "4"};
 
    public static void main(String[] args) {
        DataSet dataSet = new DataSet();
        Iterator<String> iterator = dataSet.iterator();
        while (iterator.hasNext()) {
            String nextValue = iterator.next();
            System.out.println("The next value with Iterator is: " + nextValue);
        }
 
        for (String nextValue : dataSet) {
            System.out.println("The next value with the for Loop is: " + nextValue);
        }
    }
 
 
    @Override
    public Iterator<String> iterator() {
        return new DataSetIterator();
    }
 
    private class DataSetIterator implements Iterator {
        private int position = 0;
 
        public boolean hasNext() {
            if (position < myData.length)
                return true;
            else
                return false;
        }
 
        public String next() {
            if (this.hasNext())
                return myData[position++];
            else
                return null;
        }
 
        @Override
        public void remove() {
 
        }
    }
 
}

Output:

The next value with Iterator is: 1
The next value with Iterator is: 2
The next value with Iterator is: 3
The next value with Iterator is: 4
The next value with the for Loop is: 1
The next value with the for Loop is: 2
The next value with the for Loop is: 3
The next value with the for Loop is: 4
Advertising

4 - Documentation / Reference

lang/java/iterator.txt · Last modified: 2017/09/20 22:34 by gerardnico