Created
September 7, 2020 02:21
-
-
Save shawnz/d7d5ab2ad4be0be05259f4b0184f4a81 to your computer and use it in GitHub Desktop.
This file contains 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
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