Monthly Archives: September 2018

Iterable Interface Example

java.lang.Iterable Interface Example




This article shows an example of Iterable interface. This is defined in java.lang package and was introduced with Java 5. The Iterable is defined as a generic type; Iterable<T>, where T type parameter represents the type of elements returned by the iterator.

An object that implements this interface allows it to be the target of the “foreach” statement. The for-each loop is used for iterating over arrays, collections etc. Collection classes and classes where iterations are useful implement this interface.

Before the iterable’s for-each loop was introduced, a way to iterate is to use the for(;;) loop or to use an Iterator; typically the Iterator could be acquired by invoking a collection object’s iterator() method. The iterator has been in Java since Java 1.2.

The Iterable interface provides a clean approach to coding the iteration functionality. An example shows iterating over a List collection with String object elements:

List stringList = new ArrayList<String>();
stringList.add("a");
stringList.add("b");
stringList.add("c");

for (String s : stringList) {
    System.out.println(s);
}

for (int i = 0; i < stringList.size(); i++) {

    System.out.println(stringList [i]);
}

Iterator iter = stringList.iterator();

while (iter.hasNext()) {

    System.out.println(iter.next());

}

Note that there is also a possibility of introducing a bug in the above two code snippets, because of the details.

1. Example

The following example class implements the Iterable interface. The class takes an input array of any type and iterates it in a for-each loop and in reverse order.

Oracle doc

The Iterable interface has one method to override: Iterator<T> iterator().

The example has the iterable implementation MyIterable.java and a tester class MyIterableTester.java.

1.1. The code

MyIterable.java

import java.util.List;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Collections;

public class MyIterable implements Iterable {

    private List list;
    public MyIterable(T [] t) {
        list = Arrays.asList(t);
        Collections.reverse(list);
    }
    @Override
    public Iterator iterator() {
        return list.iterator();
    }

}

MyIterableTester.java

public class MyIterableTester {

    public static void main(String [] args) {

        Integer [] ints = {1, 2, 3};

        MyIterable myList = new MyIterable<>(ints);

        for (Integer i : myList) {
            System.out.println(i);
        }

    }

}

1.2. The output

3
2
1

2. Download Java Source Code

This was an example of java.lang.Iterable Interface Example.

Download
You can download the full source code of this example here: IterableExample.zip