1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
| public class CycleIterator<T> implements Iterator<T> {
private Iterable<T> iterable;
private int max;
private int nb;
private Iterator<T> iterator;
private boolean remove;
private IStopCondition<T> stopCondition;
private Boolean hasNext;
private int cyclecount;
public CycleIterator(Iterable<T> iterable) {
this(iterable, null);
}
public CycleIterator(Iterable<T> iterable, IStopCondition<T> stopCondition) {
this.iterable=iterable;
this.max=-1;
this.stopCondition=stopCondition;
}
public CycleIterator(Iterable<T> iterable, int max) {
this.iterable=iterable;
this.max=max<0?0:max;
}
public boolean hasNext() {
hasNext=null;
if ( max>=0 && nb>=max ) {
hasNext = false;
}
else if ( iterator==null || !iterator.hasNext() ) {
iterator=iterable.iterator();
if ( stopCondition.stopOnCycle(iterator, cyclecount) || !iterator.hasNext() ) {
hasNext = false;
}
cyclecount++;
}
if ( hasNext==null && stopCondition!=null ) {
if ( stopCondition.stop(iterator) ) {
hasNext = false;
}
}
if ( hasNext==null ) {
hasNext=true;
}
return hasNext;
}
public T next() {
if ( hasNext==null ) {
hasNext();
}
if ( hasNext ) {
remove=true;
hasNext=null;
nb++;
return iterator.next();
}
throw new NoSuchElementException();
}
public void remove() {
if ( remove ) {
iterator.remove();
remove=false;
}
else {
throw new IllegalStateException();
}
}
public static interface IStopCondition<U> {
boolean stop(Iterator<U> iter);
boolean stopOnCycle(Iterator<U> iter, int cycleCount);
}
/*public static void main(String[] args) {
List<String> list = new ArrayList<String>();
for(int i=0; i<10; i++) {
list.add(String.valueOf(i));
}
class Tester {
void test(Iterator<String> iter) {
int n=0;
for( ; iter.hasNext(); ) {
System.out.println(n++ + " " +iter.next());
}
}
void testrem(Iterator<String> iter) {
int n=0;
for( ; iter.hasNext(); ) {
System.out.println(n++ + " " +iter.next());
if ( n%2==0 ) {
iter.remove();
}
}
}
}
//new Tester().test(new CycleIterator<String>(list, 45));
//new Tester().test(new CycleIterator<String>(list, 5));
//new Tester().test(new CycleIterator<String>(list.subList(0, 0), 5));
//new Tester().testrem(new CycleIterator<String>(list, 15));
//new Tester().testrem(new CycleIterator<String>(list));
new Tester().test(new CycleIterator<String>(list, new IStopCondition<String>() {
public boolean stop(Iterator<String> iter) {
return !iter.hasNext() || Math.random()<0.5;
}
public boolean stopOnCycle(Iterator<String> iter, int cycleCount) {
return false;
}
}));
}*/
} |
Partager