Friday 29 September 2017

Implement Array Iterator

Array Iterator is used to traverse elements of the array. Implement Array Iterator such that, it should satisfy below requirements.

a.   Array Iterator should take starting offset (offset=0 represents start the iteration from 0th index element) and number of elements to iterate.
b.   Array Iterator should not support removal of elements.
c.   Array Iterator throws exception if offset + numberOfElementsToIterate > number of elements in array
d.   Array Iterator should be generic, it should take any kind of reference type.
e.   Throw PreconditionFailedException on failure of preconditions on array iterator initialization.

PreconditionFailedException.java
package com.sample.exception;

public class PreconditionFailedException extends Exception {

 private static final long serialVersionUID = 1L;
 
 public PreconditionFailedException(String message){
  super(message);
 }

}

ArrayIterator.java
package com.sample.util;

import java.util.Iterator;

import com.sample.exception.PreconditionFailedException;

public class ArrayIterator implements Iterator<Object> {

 private final Object[] arr;
 private int offset;
 private final int end;

 /**
  * 
  * @param arr
  * @param offset
  *            Starting point to iterate from array
  * @param noOfElements
  *            number of elements to iterate from offset
  * @throws PreconditionFailedException
  *             on failure of preconditions
  */
 public ArrayIterator(Object[] arr, int offset, int noOfElements) throws PreconditionFailedException {
  if (arr == null) {
   throw new NullPointerException("arr should not be null");
  }

  if (arr.length < offset) {
   throw new PreconditionFailedException("offset should be less than array length");
  }

  if (offset < 0) {
   throw new PreconditionFailedException("offset should be >= 0. offset : " + offset);
  }

  if (noOfElements <= 0) {
   throw new PreconditionFailedException("noOfElements should be > 0. noOfElements : " + noOfElements);
  }

  if (arr.length < (offset + noOfElements)) {
   throw new PreconditionFailedException("Array length is < (offset + noOfElements): array length : "
     + arr.length + ", offset : " + offset + ", noOfElements : " + noOfElements);

  }

  this.arr = arr;
  this.offset = offset;
  end = offset + noOfElements;
 }

 @Override
 public boolean hasNext() {
  return offset < end;
 }

 @Override
 public Object next() {
  return arr[offset++];
 }

}

Test.java
package com.sample.test;

import com.sample.exception.PreconditionFailedException;
import com.sample.util.ArrayIterator;

public class Test {
 public static void main(String args[]) throws PreconditionFailedException {
  Integer[] arr = new Integer[10];

  for (int i = 0; i < arr.length; i++) {
   arr[i] = i;
  }

  ArrayIterator arrIterator = new ArrayIterator(arr, 3, 6);

  while (arrIterator.hasNext()) {
   System.out.println(arrIterator.next());
  }
 }
}


No comments:

Post a Comment