Generator (computer programming): Difference between revisions

Content deleted Content added
Java: clearer
Java: fixes; clarity
Line 226:
=== Java ===
[[Java (programming language)|Java]] does not have [[continuation]] functionality as part of the language ''per se''; however, one may easily obtain that by providing a custom implementation of some known collection or iterator interface. This will typically be the <tt>java.lang.Iterable</tt> interface, or a [[Java collections framework]] interface, but it might even be a custom collection interface.<br/>
The continuation is implemented through a [[finite-state machine]], namely an object, that will compute the single elements on the flydemand, instead of retrieving them from a real collection or storage. This will be hidden behind the collection interface, and therefore will be transparent to the application, which only "sees" the iterator or collection methods of that object, and does not know about its implementation internals, thanks to [[Encapsulation (object-oriented programming)|encapsulation]].<br/>
This means that, although continuations are not available as part of the language, you can easily get them through an OOP solution, specifically through [[Polymorphism_in_object-oriented_programming|polymorphism]].
 
It is strongly advised that this technique be used whenever it is applicable. For example, it is often applied when implementing somea ''very simple'' implementationsimplementation of modelsa [[Model–view–controller|model]] for a list or table in a [[Swing (Java)|Swing]] application: the model is implemented so that is generates theits contents ofon the modelfly, as soon as there is the need for any of them to be displayed on the flygraphical component, and this is completely transparent to the Swing library, because it just sees a collection of elements.
 
It is also important to notice that, as long as the generator object implements interface <tt>java.lang.Iterable</tt>, it may be used to control a ''for each'' statement.
Line 236:
Let's take an example. The following code defines a subclass of the the J2SE class AbstractList, to implement an unmodifiable list<ref>[http://download.oracle.com/javase/6/docs/api/java/util/AbstractList.html java.util.AbstractList]</ref>:
<source lang="Java">
// Implements a fixed-size list, that contains all numbers
// from 0 to some given number.
public class Generator extends AbstractList<Integer> {
private int _size;
// The collection will contain all numbers
// from 0 to size-1, inclusive.
public Generator(int size) {
if (size < 0) throw new IllegalArgumentException("Negative size not allowed");
Line 260 ⟶ 264:
All of the collections in the [[Java collections framework]] implement <tt>java.lang.Iterable</tt>, therefore such a list can be used in a ''for each'' statement, for example:
<source lang="java">
for(int value: new Generator(7, 20))
{
System.out.println("generator: " + value);