Even though this kind of design is nothing but ridiculous, and just to entertain your question, you can write this:
public class Container implements Iterable<String>, Iterator<String> {
@Override public Iterator<String> iterator() { return this; }
... everything else you envision for your class ...
}
Then you'll be able to use
for (String s : container)
You may write this as a learning experience, but I strongly advise you never to try it on a real project. The main reason against it is the expectation on the iterator
method to always return a fresh, independent iterator, while this implementation achieves the opposite. To give a specific example, imagine someone needing to iterate over the Cartesian product of your container with itself:
for (String s1 : container)
for (String s2 : container)
processPair(s1, s2);
Every Java programmer will tell you that, beyond any doubt, processPair
will be called with each possible pair from the container. The behavior they would instead see from your class would make their heads spin. If a bug in production was ever traced to this implementation, your teammates would... let's just say they wouldn't appreciate it.