58

I think most coders have used code like the following :


ArrayList<String> myStringList = getStringList();
for(String str : myStringList)
{
   doSomethingWith(str);
}

How can I take advantage of the for each loop with my own classes? Is there an interface I should be implementing?

3 Answers 3

59

You can implement Iterable.

Here's an example. It's not the best, as the object is its own iterator. However it should give you an idea as to what's going on.

Sign up to request clarification or add additional context in comments.

2 Comments

Implementation which have both Iterator<> and Iterable<> implemented has side effect: blog.dreasgrech.com/2010/03/javas-iterators-and-iterables.html ("An Iterator should not be Iterable!" section). Be warned.
In this example, no new iterators are being created. Doesn't this only work for one iteration because this is always being returned?
22

The short version of for loop (T stands for my custom type):

for (T var : coll) {
    //body of the loop
}

is translated into:

for (Iterator<T> iter = coll.iterator(); iter.hasNext(); ) {
    T var = iter.next();
    //body of the loop
}

and the Iterator for my collection might look like this:

class MyCollection<T> implements Iterable<T> {

    public int size() { /*... */ }

    public T get(int i) { /*... */ }

    public Iterator<T> iterator() {
        return new MyIterator();
    }

    class MyIterator implements Iterator<T> {

        private int index = 0;

        public boolean hasNext() {
            return index < size();
        }

        public type next() {
            return get(index++);
        }

        public void remove() {
            throw new UnsupportedOperationException("not supported yet");

        }
   }
}

1 Comment

Thank you, searched the internet for this
10

You have to implement the Iterable interface, that is to say, you have to implement the method

class MyClass implements Iterable<YourType>
{
Iterator<YourType> iterator()
  {
  return ...;//an iterator over your data
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.