Created
October 31, 2012 14:53
-
-
Save pfirpfel/3987471 to your computer and use it in GitHub Desktop.
Generic Array Iterator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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