COBOL | Java |
---|---|
$set ilusing(System.Collections.Generic) class-id Iterators. method-id Use static. perform varying i as binary-long thru GetSequence() display i end-perform declare #instance = new Iterators() perform varying i as binary-long thru #instance display i end-perform end method. iterator-id GetSequence static yielding retn as binary-long. declare c as binary-long = 1 perform until exit add 1 to c *> yield the next number set retn to c goback if c < 5 *> yield the next number set retn to c * 10 goback else *> end the iterator exit iterator end-if end-perform end iterator. *> Define an iterator for the current class iterator-id self yielding retn as binary-long. perform varying i as binary-long from 23 by -5 until i < 0 set retn to i goback end-perform end iterator. end class. |
// Java does not support coroutines so iterators can only be implemented // as classes that implement java.util.Iterator. import java.util.Iterator; class iterators implements Iterable<Integer> { public static void Use() { for (Iterator seq = new GetSequence(); seq.hasNext(); ) { System.out.println(seq.next()); } iterators instance = new iterators(); for (int i : instance) { System.out.println(i); } } static class GetSequence implements Iterator<Integer> { private boolean nextIsMultiplied = false; private int c = 1; public boolean hasNext() { return c < 5; } public Integer next() { if (!nextIsMultiplied) { nextIsMultiplied = true; // yield the next number c++; return c; } else { nextIsMultiplied = false; // yield the next number return c * 10; } } } // Define an iterator for the current class public Iterator<Integer> iterator() { return new GetOtherIterator(); } // Our iterator class that is created when iterating this instance static class GetOtherIterator implements Iterator<Integer> { private int i = 23; public boolean hasNext() { return i >= 0; } public Integer next() { int result = i; i -= 5; return result; } } } |
Portions of these examples were produced by Dr. Frank McCown, Harding University Computer Science Dept, and are licensed under a Creative Commons License.