11 Dec 2017

write a program in java to Implementing our own Custom Iterator of ArrayList.


To create our own custom iterator we have to follow these steps, which are described below.


Step 1:- First create your own custom class that implements the Iterable interface to return an iterator.and compile this file,  the code is following..

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

public class Animal implements Iterable {

          private ArrayList animal = new ArrayList();

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

          public ArrayList getAnimal() {
                   return animal;
          }
         
          @Override
          public Iterator iterator() {
                   return new AnimalIterator(this);
          }

}

Step 2:- now let create an iterator AnimalIterator for Animal class..and compile this file,the code is following..

import java.util.ArrayList;
import java.util.Iterator;
public class AnimalIterator implements Iterator {

          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);
          }

}

Step 3:- Now create a main class having name TestIterator. compile and run this file.

import java.util.ArrayList;

public class TestIterator {

          public static void main(String args[]) {
                   ArrayList 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);
                   }
          }
}


Output: