In my experience, the most
important consideration is whether the item in question should be able
to be traversed more than once. This is because you can always rewind an
Iterator is single traversal.
In Java 5
Iterable
by calling iterator()
again, but there is no way to rewind an Iterator
.Iterator is single traversal.
In Java 5
- Iterable<SomeObj> objs = new Iterable
>() { - public Iterator<SomeObj> iterator() {
- return object.getChildren();
- }
- };
In Java 8, working with legacy
Iterator
-based interfaces is a little easier, thanks to method references. The Service.getPorts
example above could be written as:
- Iterable<SomeObj> objs = object::getChildren;
And you can even inline it directly into the
for
loop:
- for (SomeObj objs : object::getChildren) {
- // ...
- }
A Collection is an Iterable... So you can write:
public static void main(String args[]) {
List<String> list = new ArrayList<String>();
list.add("a string");
Iterable<String> iterable = list;
for (String s : iterable) {
System.out.println(s);
}
}
No comments:
Post a Comment