Skip to main content

for-each for Iterable objects

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

Hi

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: http://www.jroller.com/page/komu/20040403#pythonic_file_iteration_in_java

Regards,
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.
patrikbeno
Offline
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

[code]
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 ) */
...
}
[/code]