T
- the element type of the IterableIterator@Deprecated
public class IterableIterator<T>
extends java.lang.Object
implements java.lang.Iterable<T>
As an example, suppose that you have a class with a method:
public Iterator<String> backwardIterator() { ... }
Because this method is not named iterator()
, which probably has a different meaning than
backwardIterator()
, it is not possible to use Java's new-style for loop (also known as
the foreach loop). Instead, a client must do:
for (Iterator<String> itor = myObject.backwardIterator(); itor.hasNext(); ) {
String element = itor.next();
...
}
The IterableIterator
class lets you write this more compactly:
for (String element : new IterableIterator(myObject.backwardIterator())) { ... }Another advantage of this syntax is that it explicitly indicates that the Iterator is not being modified in the loop body, which is a common reason for not using the new-style for loop.
It's often better to use a real Iterable (e.g., a collections class) rather than an Iterator. But in some cases the overhead is undesirable, or there are multiple ways to iterate so it doesn't make sense to reserve the iterator() method for just one of them, or it is desirable to use an Iterator because it throws a ConcurrentModificationException in case of errors, or for other reasons. This class can be appropriate in such circumstances.
Warning: Some clients might expect that calling Iterable.iterator() twice on a given Iterable results in two objects that can both iterate over the whole sequence, and that won't interfere with one another. That is not the case for this Iterable.
Constructor and Description |
---|
IterableIterator(java.util.Iterator<T> iter)
Deprecated.
Create an IterableIterator.
|
Modifier and Type | Method and Description |
---|---|
java.util.Iterator<T> |
iterator()
Deprecated.
Return the iterator.
|
public IterableIterator(java.util.Iterator<T> iter)
iter
- the iterator to wrap