marizal marizal - 1 year ago 103
Java Question

What's the difference between returning an Iterator and an unmodifiable list?

From what I understand, both are used to return unmodifiable objects, but why would one be used over the other?

Edit: My mistake, Iterators are not unmodifiable. But I'm still unclear on why an Iterator might be used instead of a List.

Answer Source

Return a List when you need a list; return an Iterator when you need an iterator. They are completely different data structures that serve different purposes.

As an aside, an Iterator might be able to modify the underlying collection through the remove() method (which removes the last item returned by next()).

Edit (in response to OP's edit): You would want to return an Iterator if you specifically wanted to prevent client code from seeing the underlying list, or you want to force sequential access to the elements. It's also required that you write an iterator() method that returns an Iterator when your class implements Iterable. There's also the interesting case of returning an Iterator that iterates through an undetermined collection of items, that might not even exist in memory until they are requested. (Think, for instance, of state space searching in an AI-based application.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download