Skip to main content

for-each for Iterable objects

1 reply [Last post]
Joined: 2003-09-14
Points: 0


I though that for-each loop construct works on any Iterable object but it looks like that the for-each loops only work on Collection objects. Wouldn't it be better if it worked on Iterable objects too?

So we could write code like this:

Behrang S.

Message was edited by: behrangsa

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
Joined: 2004-10-11
Points: 0

But it works on any Iterable! That's why Iterable was introduced in Tiger (or at least one of the reasons)

You just have to say what type you iterate (using generics);
You cannot iterate raw Iterable but you can iterate Iterable

Iterable iterable = ...;
for (String s : iterable) { /* won't compile because iterable is raw Iterable */

Iterable strings = ...;
for (String s : strings) { /* this works because type parameter is known (Interable ) */