Skip to content

Instantly share code, notes, and snippets.

@deyindra
Created December 1, 2014 16:05
Show Gist options
  • Save deyindra/0f94d9e04893f1651236 to your computer and use it in GitHub Desktop.
Save deyindra/0f94d9e04893f1651236 to your computer and use it in GitHub Desktop.
ArrayBasedListIterator
import java.util.ListIterator;
import java.util.NoSuchElementException;
public class ArrayBasedListIterator<T> implements ListIterator<T> {
private T[] array;
private int current;
private int prevIndex;
private int nextIndex;
public ArrayBasedListIterator(T[] array) {
this.array = array;
this.current = 0;
prevIndex = -1;
nextIndex = 0;
}
@Override
public boolean hasNext() {
return (array!=null && array.length!=0 && nextIndex<array.length);
}
@Override
public T next() {
if(!hasNext()){
throw new NoSuchElementException("No more element");
}
current = nextIndex;
prevIndex = nextIndex;
nextIndex++;
return array[current];
}
@Override
public boolean hasPrevious() {
return (array!=null && array.length!=0 && prevIndex>=0);
}
@Override
public T previous() {
if(!hasPrevious()){
throw new NoSuchElementException("No more element");
}
current = prevIndex;
nextIndex = prevIndex;
prevIndex--;
return array[current];
}
@Override
public int nextIndex() {
if(!hasNext()){
throw new NoSuchElementException("No more element");
}
return nextIndex;
}
@Override
public int previousIndex() {
if(!hasPrevious()){
throw new NoSuchElementException("No more element");
}
return prevIndex;
}
@Override
public void remove() {
throw new UnsupportedOperationException("Remove");
}
@Override
public void set(T t) {
throw new UnsupportedOperationException("set");
}
@Override
public void add(T t) {
throw new UnsupportedOperationException("add");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment