Skip to content

Instantly share code, notes, and snippets.

@shawnz
Created September 7, 2020 02:21
Show Gist options
  • Save shawnz/d7d5ab2ad4be0be05259f4b0184f4a81 to your computer and use it in GitHub Desktop.
Save shawnz/d7d5ab2ad4be0be05259f4b0184f4a81 to your computer and use it in GitHub Desktop.
import java.util.*;
public class LazyList<E> extends AbstractSequentialList<E> {
private final ArrayList<E> cache = new ArrayList<>();
private final Iterator<E> iterator;
private final int size;
public LazyList() {
this.iterator = Collections.emptyIterator();
this.size = 0;
}
public LazyList(Iterator<E> iterator, int size) {
this.iterator = iterator;
this.size = size;
}
@Override
public ListIterator<E> listIterator(int index) {
if (index < 0 || index > size)
throw new IndexOutOfBoundsException();
while (index > cache.size()) {
if (!iterator.hasNext())
throw new IndexOutOfBoundsException();
cache.add(iterator.next());
}
return new LazyListIterator(cache.listIterator(index));
}
@Override
public int size() {
return size;
}
public int cacheSize() {
return cache.size();
}
private class LazyListIterator implements ListIterator<E> {
private final ListIterator<E> cacheListIterator;
public LazyListIterator(ListIterator<E> cacheListIterator) {
this.cacheListIterator = cacheListIterator;
}
@Override
public boolean hasNext() {
return cacheListIterator.hasNext() || iterator.hasNext();
}
@Override
public E next() {
if (cacheListIterator.hasNext())
return cacheListIterator.next();
E next = iterator.next();
cacheListIterator.add(next);
return next;
}
@Override
public boolean hasPrevious() {
return cacheListIterator.hasPrevious();
}
@Override
public E previous() {
return cacheListIterator.previous();
}
@Override
public int nextIndex() {
return cacheListIterator.nextIndex();
}
@Override
public int previousIndex() {
return cacheListIterator.previousIndex();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
public void set(E e) {
throw new UnsupportedOperationException();
}
@Override
public void add(E e) {
throw new UnsupportedOperationException();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment