Hi guys,

First off I would like to mention that I am not an experienced Java programmer. I've been programming for about a year and taken one AP level course in high school. With the exam in a few days, I was wondering if anyone could clear something up for me about the For-each loop.

Basically, on a practice free response I did (hand writing code, essentially) I used the for-each loop syntax for traversing a WordSet. The code for the WordSet class is given, it essentially stores a set of String objects. It shows no implementation of interfaces, or extension of other classes (specifically the Iterable interface, which someone told me was required for the for-each loop to work on said class).

After writing it I was told that the for-each loop can not be used for such a collection, but doing a bit of follow up research I cannot seem to find a clear cut answer! I know it works for Arrays and Collections(ex. ArrayList), but I don't know if WordSet constitutes a collection. Please let me know if the for-each loop would work for such a class, or if I have not given any information, how I could find out!

Thank you so much!

If the "WordSet" class implements a Collection/List/Map interface (or extends a Class that does so), then yes, it can be used, otherwise, no, it can't. Now, whether or not you can use it for this "WordSet" Class, I can't say, as I have no idea what the class looks like.

Without access to the source of that class (see above) you can still just try coding a for-each on it and see if it compiles!

This article has been dead for over six months. Start a new discussion instead.