×

Welcome to TagMyCode

Please login or create account to add a snippet.
1
0
 
0
Language: Java
Posted by: Richard McDonald
Added: May 8, 2014 3:28 AM
Views: 1833
Tags: array iterator
  1. public class ArrayIterator<E> implements Iterator<E> {
  2.         private E array[];
  3.         private int position = 0;
  4.  
  5.         public ArrayIterator(E array[]) {
  6.                 this.array = array;
  7.         }
  8.  
  9.         @Override
  10.         public boolean hasNext() {
  11.                 while (position < array.length) {
  12.                         if (array[position] != null) {
  13.                                 break;
  14.                         }
  15.                         position++;
  16.                 }
  17.                 return position < array.length;
  18.         }
  19.  
  20.         @Override
  21.         public E next() {
  22.                 if (hasNext()) {
  23.                         return array[position++];
  24.                 } else {
  25.                         throw new NoSuchElementException();
  26.                 }
  27.         }
  28. }

1 comment

Richard McDonald 8 years ago
Note that null values in the array are not included in the iterator.

Write a comment