Creative_Cimmons
Creative_Cimmons

Reputation: 265

Explanation on the specific example of iterator needed

With due credits to Joe and his site javapapers.com,

I need explanation about the following code which I came across while browsing about iterators in java

package com.javapapers;

import java.util.ArrayList;
import java.util.Iterator;

      public class AnimalIterator<String> implements Iterator<Object> {

    private ArrayList<?> animal;
      private int position;

     public AnimalIterator(Animal animalBase) {
    this.animal = animalBase.getAnimal();
  }

     @Override
     public boolean hasNext() {
    if (position < animal.size())
      return true;
      else
      return false;
     }

     @Override
       public Object next() {
      Object aniObj = animal.get(position);
      position++;
      return aniObj;
     }

      @Override
     public void remove() {
    animal.remove(position);
     }

    }
     package com.javapapers;

     import java.util.ArrayList;
     import java.util.Iterator;

     public class Animal implements Iterable<String> {

      private ArrayList<String> animal = new ArrayList<String>();

     public Animal(ArrayList animal){
    this.animal = animal;
      }

     public ArrayList getAnimal() {
      return animal;
     }

      @Override
       public Iterator<String> iterator() {
      return new AnimalIterator(this);
          }

     }
       package com.javapapers;

      import java.util.ArrayList;

         public class TestIterator {

       public static void main(String args[]) {
        ArrayList<String> animalList = new ArrayList();
        animalList.add("Horse");
         animalList.add("Lion");
         animalList.add("Tiger");
       Animal animal = new Animal(animalList);  
        for (String animalObj : animal) {       ??
         System.out.println(animalObj);         ??
        }
       }
      }

My doubt is in ??, here we define for loop to iterate over the animal object defined, but i don't understand how Iterator is being used here.

source

http://javapapers.com/core-java/java-iterator/

Upvotes: 1

Views: 186

Answers (1)

Harmlezz
Harmlezz

Reputation: 8068

The expression:

for (Type item : items) {
}

is called the foreach-loop in Java. It works for every type which implements Iterable<T>. It can be translated into:

for (Iterator<Type> iter = items.iterator(); iter.hasNext(); ) {
    Type item = iter.next();
}

Hence, the iterator is used implicitly, invisible for your eyes in the foreach-loop.

Upvotes: 1

Related Questions