www.000webhost.com
/** * Created by PhpStorm. * User: Rahul * Date: 12/8/2016 * Time: 8:09 PM */ Iterable interface


Iterable Interface


Core Java

The Iterable interface (java.lang.Iterable) is one of the root interfaces of the Java collection classes. The Collection interface extends Iterable, so all subtypes of Collection also implement the Iterable interface.

A class that implements the Iterable can be used with the new for-loop - example:

		List list = new ArrayList();
		
		for(Object o : list){
		    //do something o;    
		}

We can iterate only in one direction

Iteration can be done only once. If you reach the end of series its done. If we need to iterate again we should get a new Iterator.


The Iterable interface has only one method:

		public interface Iterable<T> {
		  public Iterator<T> iterator();    
		}

Iterator Example without Generics

		package com.javaessential;
		 
		import java.util.ArrayList;
		import java.util.Iterator;
		 
		public class ExampleIterator {
		 
		  public static void main(String args[]){
		    ArrayList animal = new ArrayList();
		    animal.add("Horse");
		    animal.add("Lion");
		    animal.add("Tiger");
		 
		    Iterator animalItr = animal.iterator();
		 
		    while(animalItr.hasNext()) {
		      String animalObj = (String)animalItr.next();
		      System.out.println(animalObj);
		    }
		  }
		 
		}

Without generics, Iterator returns the Object and we need to typecast it.



Iterator Example using Generics

		package com.javaessential;
		 
		import java.util.ArrayList;
		 
		public class ExampleIterator {
		 
		  public static void main(String args[]){
		    ArrayList<String> animal = new ArrayList<String>();
		    animal.add("Horse");
		    animal.add("Lion");
		    animal.add("Tiger");
		 
		    for(String animalObj : animal) {
		      System.out.println(animalObj);
		    }
		  }
		}

Iterable and Iterator

To make an object iterable it needs to emit an Iterator object. To enforce this contract, Iterator interface is to be used.
It contains a method named iterator() and it returns Iterator. Hence, any class that implements Iterable will return an Iterator.

public interface Collection<E> extends Iterable<E> {

A Collection is an interface that represents container for series of elements. Every collections like ArrayList, Vector implements Collection and so Iterator. One advantage of Iterable is, when you implement Iterable then those object gets support for for:each loop syntax.


ConcurrentModificationException in Iterator

We cannot add or remove elements to the underlying collection when we are using an iterator - it throws ConcurrentModificationException.


		package com.javaessential;
		 
		import java.util.ArrayList;
		 
		public class ExampleIterator {
		 
		  public static void main(String args[]){
		    ArrayList<String> animal = new ArrayList<String>();
		    animal.add("Horse");
		    animal.add("Lion");
		    animal.add("Tiger");
		 
		    for(String animalObj : animal) {
		      System.out.println(animalObj);
		      animal.add("Hyena");
		    }
		  }
		}
		 
		Output:
		Horse
		Exception in thread "main" java.util.ConcurrentModificationException
		  at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
		  at java.util.ArrayList$Itr.next(Unknown Source)
		  at com.javaessential.ExampleIterator.main(ExampleIterator.java:13)


Difference between iterator and iterable with Example

An Iterable is a simple representation of a series of elements that can be iterated over. It does not have any iteration state such as a "current element". Instead, it has one method that produces an Iterator.

An Iterator is the object with iteration state. It lets you check if it has more elements using hasNext() and move to the next element (if any) using next().

Typically, an Iterable should be able to produce any number of valid Iterators.

If a collection is iterable, then it can be iterated using an iterator (and consequently can be used in a for each loop.) The iterator is the actual object that will iterate through the collection.


//An implementation of Iterable is one that provides an Iterator of itself:

		public interface Iterable<T>
		{
		    Iterator<T> iterator();
		}

//An iterator is a simple way of allowing some to loop through a collection of data 
without assignment privileges (though with ability to remove).

		public interface Iterator<E>
		{
		    boolean hasNext();
		    E next();
		    void remove();
		}


Creating custom iterators

if we want our own custom iterator. We can use Java's java.util.Iterator interface to build our own iterator. so that it returns an Iterator using which we can iterate the elements.
In the following example, I have created a Circular Iterator:


Creating custom iterators with Example

		public class CircularGamesIterator implements Iterator<Game> {
		
		 private Vector<Game> list;
		 private int currentPosition;
		 
		 public CircularGamesIterator(Vector<Game> games) {
		  list = games;
		  currentPosition = 0;
		 }
		 
		 @Override
		 public boolean hasNext() {
		  return currentPosition < list.size();
		 }
		
		 @Override
		 public Game next() {
		  Game el = list.elementAt(currentPosition);
		  currentPosition = (currentPosition + 1) % list.size(); 
		  return el;
		 }
		
		 @Override
		 public void remove() { }
		}

The iterator() method of the GameCollection class can then be modified to return an instance of the CircularGamesIterator:

		public class GameCollection implements Iterable<Game> {
		 private Vector<Game> games;
		 
		 public GameCollection() {
		  games = new Vector<Game>();
		 }
		 
		 public void add(Game game) {
		  games.add(game);
		 }
		
		 @Override
		 public Iterator<Game> iterator() {
		  return new CircularGamesIterator(games);
		 }
		}

Click here to go On Collection Home Page