2015-09-07 11:44:36 -06:00
|
|
|
// innerclasses/Sequence.java
|
2016-12-30 17:23:13 -08:00
|
|
|
// (c)2017 MindView LLC: see Copyright.txt
|
2015-11-15 15:51:35 -08:00
|
|
|
// We make no guarantees that this code is fit for any purpose.
|
2016-09-23 13:23:35 -06:00
|
|
|
// Visit http://OnJava8.com for more book information.
|
2016-01-25 18:05:55 -08:00
|
|
|
// Holds a sequence of Objects
|
2015-06-15 17:47:35 -07:00
|
|
|
|
|
|
|
interface Selector {
|
|
|
|
boolean end();
|
|
|
|
Object current();
|
|
|
|
void next();
|
|
|
|
}
|
|
|
|
|
|
|
|
public class Sequence {
|
|
|
|
private Object[] items;
|
|
|
|
private int next = 0;
|
2016-01-25 18:05:55 -08:00
|
|
|
public Sequence(int size) {
|
|
|
|
items = new Object[size];
|
|
|
|
}
|
2015-06-15 17:47:35 -07:00
|
|
|
public void add(Object x) {
|
|
|
|
if(next < items.length)
|
|
|
|
items[next++] = x;
|
|
|
|
}
|
|
|
|
private class SequenceSelector implements Selector {
|
|
|
|
private int i = 0;
|
|
|
|
@Override
|
|
|
|
public boolean end() { return i == items.length; }
|
|
|
|
@Override
|
|
|
|
public Object current() { return items[i]; }
|
|
|
|
@Override
|
|
|
|
public void next() { if(i < items.length) i++; }
|
|
|
|
}
|
|
|
|
public Selector selector() {
|
|
|
|
return new SequenceSelector();
|
|
|
|
}
|
|
|
|
public static void main(String[] args) {
|
|
|
|
Sequence sequence = new Sequence(10);
|
|
|
|
for(int i = 0; i < 10; i++)
|
|
|
|
sequence.add(Integer.toString(i));
|
|
|
|
Selector selector = sequence.selector();
|
|
|
|
while(!selector.end()) {
|
|
|
|
System.out.print(selector.current() + " ");
|
|
|
|
selector.next();
|
|
|
|
}
|
|
|
|
}
|
2015-09-07 11:44:36 -06:00
|
|
|
}
|
|
|
|
/* Output:
|
2015-06-15 17:47:35 -07:00
|
|
|
0 1 2 3 4 5 6 7 8 9
|
2015-09-07 11:44:36 -06:00
|
|
|
*/
|