Generator (computer programming): Difference between revisions

Content deleted Content added
Java: added an example
Line 268:
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.
 
Even simple iterators built this way tend to be significantly bulkier than those using generators, with a lot of [[boilerplate code]].
 
<source lang="java">
// Iterator implemented as anonymous class.
foreach (int i : new Iterator(){
static int counter=0;
public boolean hasNext() {counter<100;}
public int next(){
while(counter<Math.sqrt(3))counter++;
return counter++;})
{
System.out.println(i);
}
</source>
 
=== C++ ===