Java methods accepting and returning Iterable<T> types are very common. The problem I see is that the Iterator interface is so limited, that it either requires one to reconstruct the Iterable into a usable data structure, or forces the users to perform multiple traversals of the Iterable, increase execution time.
Can someone correct me on this? Are Iterables as bad as I think they are? Are there any techniques that one can use to work-around the limitation of Iterables if you are forced to use them?
Regarding accepting an
Iterable<T>this is clearly a good thing. It means you can pass it almost any data structure – it only needs to implement the very simpleIterable<T>interface. This makes the code easier to reuse.For returning an
Iterable<T>one of the advantages is that the implementation of the method can change – perhaps using a more efficient data structure, or by generating the results lazily as they are requested (e.g. streaming them from disk). It is easy to change the implementation without breaking your clients, because they only depend on theIterable<T>interface. If you had exposed aList<T>then you can’t be sure that your clients will access the data in sequential order.You are right that if you need to access the results more than once then it would make sense to first copy the data into a different structure. But only you know what specific collection is most useful for your specific situation. Sometimes it could be an
ArrayList. Other times you might prefer to store the items in aHashMap. So you would often have to copy the data into a new data structure anyway.