Generator (computer programming): Difference between revisions

Content deleted Content added
Jespdj (talk | contribs)
Java: Fixed invalid Java examples. An Iterator is not an Iterable, and cannot be used directly in a foreach-loop.
Line 304:
 
===Java===
Java has had a standard interface for implementing iterators since its early days, and since Java 5, the "foreach" construction makes it easy to loop over iteratorsobjects that provide the <tt>java.lang.Iterable</tt> interface. (The [[Java collections framework]] and other collections frameworks, typically provide iterators for all collections.)
 
However, [[Java (programming language)|Java]] does not have generators built into the language. This means that creating iterators is often much trickier than in languages with built-in generators, especially when the generation logic is complex. Because all state must be saved and restored every time an item is to be yielded from an iterator, it is not possible to store state in local variables or use built-in looping routines, as when generators are available; instead, all of this must be manually simulated, using object fields to hold local state and loop counters.
Line 313:
<source lang="Java">
// Iterator implemented as anonymous class. This uses generics but doesn't need to.
for (int i: new IteratorIterable<Integer>() {
int counter = 1;
@Override
public booleanIterator<Integer> hasNextiterator() {
return counternew Iterator<=Integer>() 100;{
int counter = 1;
 
@Override
public Integerboolean nexthasNext() {
return counter++ <= 100;
b = total; }
 
@Override
public voidInteger removenext() {
return counter++;
}
 
@Override
public void remove() {
throw new UnsupportedOperationException();
}
int a = 1 };
}
}) {
@Override
public Integer next() {
return counter++;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}) {
System.out.println(i);
}
Line 337 ⟶ 342:
An infinite Fibonacci sequence could also be written as an Iterator:
<source lang="java">
IteratorIterable<Integer> fibo = new IteratorIterable<Integer>() {
int a = 1;
int b = 1;
int total;
 
@Override
public booleanIterator<Integer> hasNextiterator() {
return true;new Iterator<Integer>() {
int a = 1;
}
int b = 1;
int total;
 
@Override
public Integerboolean nexthasNext() {
total = a + b return true;
a = b; }
 
b = total;
return total; @Override
public Integer next() {
}
total = a + b;
a = b;
b = total;
return total;
}
 
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
// this could then be used as...
while (fibo.hasNext()) {