Content deleted Content added
→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
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
int counter = 1;▼
@Override
public
return
▲ int counter = 1;
@Override▼
@Override▼
return counter++;
}
@Override
public void remove() {
throw new UnsupportedOperationException();▼
}
}
▲ @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">
▲ int a = 1;
int b = 1;▼
int total;▼
@Override
public
return
int a = 1;
}▼
▲ int b = 1;
▲ int total;
@Override
public
▲ b = total;
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()) {
|