Whimusical
Whimusical

Reputation: 6649

Returning Iterator instead of Collection

Is there any advantage or where returning a iterator is more desirable that a collection in methods for data access layer?

I´ve seen it somewhere, and don´t remember why.

P.S: Maybe it has to do with realtime fetching of some data while is not complete

Upvotes: 2

Views: 789

Answers (2)

Michael Borgwardt
Michael Borgwardt

Reputation: 346536

A JDBC ResultSet basically works like that, though it's a different and more complex interface. And yes, the reason for that is that it allows processing huge datasets without first fetching them entirely into memory.

Also, some other languages (C++ and Python, I belive) idiomatically use iterators as data items to be passed around. In Java, this is generally not done and should be avoided (unless there is a compelling reason) because Java's iterators lack some important functionality that makes them much less useful than a Collection - namely, you cannot copy them or reset their position.

Upvotes: 2

Marius Ion
Marius Ion

Reputation: 387

The Iterator has a much simpler interface than the Collection, and should be easier to implement a custom wrapper that does things the way you want them.

As you mentioned, you can implement it such that the next() method blocks until the data is available. Also, you can choose to not implement the remove() operation and thus not allow the caller to alter the underlying collection.

Upvotes: 2

Related Questions