Skip to content

Instantly share code, notes, and snippets.

@pfirpfel
Created October 31, 2012 14:53
Show Gist options
  • Save pfirpfel/3987471 to your computer and use it in GitHub Desktop.
Save pfirpfel/3987471 to your computer and use it in GitHub Desktop.
Generic Array Iterator
package pfirpfel;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class ArrayIterator<E> implements Iterator<E> {
private E[] array;
private int index = 0;
private boolean lastRemoved = false;
public ArrayIterator(E[] array) {
this.array = array;
}
@Override
public boolean hasNext() {
return (index < array.length);
}
@Override
public E next() {
if (index <= array.length)
throw new NoSuchElementException("No element at index: " + index);
E object = array[index];
index++;
lastRemoved = false;
return object;
}
@Override
public void remove() {
if (index == 0 || lastRemoved)
throw new IllegalStateException();
array[index - 1] = null;
lastRemoved = true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment