No. 2 - Data Structure with even print iterator


Problem:


Create a data structure using array whose iterator print values at even indices of array.

Solution:


In the iterator maintain a counter, initilise with zero and on returning next element, increment by 2. In hasNext() method if the counter is less that the size of the array return true. In next() method return object at index equal to counter and increment it by 2.

Example:


DataStructureWithEvenPrintIterator.java
package com.meritmix.blog.algo;
/**
 * @author Ravi Yadav
 * This is copyright content of MeritMix.com
 * blog address is blog.meritmix.com 
 */
public class DataStructureWithEvenPrintIterator {
    //create an array
    private final static int SIZE = 15;
    private int[] arrayOfInts = new int[SIZE];
    
    public DataStructureWithEvenPrintIterator() {
        //fill the array with ascending integer values
        for (int i = 0; i < SIZE; i++) {
            arrayOfInts[i] = i;
        }
    }
    
    public void printEven() {
        //print out values of even indices of the array
        InnerEvenIterator iterator = this.new InnerEvenIterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.getNext() + " ");
        }
    }
    
//inner class implements the Iterator pattern
    private class InnerEvenIterator {
        //start stepping through the array from the beginning
        private int next = 0;
        
        public boolean hasNext() {
            //check if a current element is the last in the array
            return (next <= SIZE - 1);
        }
        
        public int getNext() {
            //record a value of an even index of the array
            int retValue = arrayOfInts[next];
            //get the next even element
            next += 2;
            return retValue;
        }
    }
    
    public static void main(String s[]) {
        //fill the array with integer values and print out only values of even indices
        DataStructureWithEvenPrintIterator ds = new DataStructureWithEvenPrintIterator();
        ds.printEven();
    }
}

No comments:

Post a Comment