import java.util.Iterator;
import java.util.NoSuchElementException;
import edu.princeton.cs.algs4.StdOut;
public class Example5 {
private static class SmallArray<T> implements Iterable<T> {
public final int K = 10;
public final T[] container;
public SmallArray(T[] elements) {
// NOTE: we do note create a defensive copy here!
container = (T[]) elements;
}
public int length() {
return Math.min(container.length, K);
}
public T get(int i) {
if (i < 0 || i >= length())
throw new IndexOutOfBoundsException();
return container[i];
}
private class SmallArrayIterator implements Iterator<T> {
private int next = 0;
public boolean hasNext() { return next >= length(); }
public void remove() { throw new UnsupportedOperationException(); }
public T next() {
if (!hasNext()) throw new NoSuchElementException();
T item = container[next];
next += 1;
return item;
}
}
public Iterator<T> iterator() {
return new SmallArrayIterator();
}
}
public static void main(String[] args) {
String[] array = { "hello", "world", "!" };
SmallArray<String> sa = new SmallArray<String>(array);
StdOut.println(sa);
// Since no defensive copy is created the example fails
for(int i = 0; i < sa.length(); i++) {
array[1] = "boom";
StdOut.println(sa.get(i));
}
}
}