You can make your class iterable:
public class Zoo implements Iterable<Animal> { ... public Iterator<Animal> iterator() { return animalList.iterator(); } }
Then you can just do something like this:
for (Animal a : zoo) { ... }
If you return an iterator, you should do it like this:
for (Animal a : zoo.iterator()) { ... }
What is redundant.
You can also write your own iterator so that the user does not call iterator.remove() and does not modify your list:
public class ReadOnlyAnimalIterator implements Iterator<Animal> { private Iterator iter; public ReadOnlyIterator(List<Animal> list) { this.iter = list.iterator(); } public boolean hasNext() { return iter.hasNext(); } public Animal next() { return iter.next(); } public void remove() { throw new UnsupportedOperationException(); } }
Then in the iterator() method:
return new ReadOnlyAnimalIterator(list);
So my answer to this question is that it would be better to make your zoo iterable, perhaps by overriding Iterator if you want to make it read-only.
source share