When should I accept a parameter of Iterable vs. Collection in Java?

后端 未结 9 1523
独厮守ぢ
独厮守ぢ 2021-01-30 01:06

What are the considerations of using Iterable vs. Collection in Java?

For example, consider implementing a type that is primarily concerned with contai

相关标签:
9条回答
  • 2021-01-30 01:26

    See "Why so much emphasis on Iterators and Iterables?" on the Google Collection FAQ for a decent argument for preferring Iterators, especially when dealing with a lot of data. One analogy that might help is to think the difference between forward-only read-only cursors and scrollable cursors.

    0 讨论(0)
  • 2021-01-30 01:29

    Users of Spring Data JPA will find that the Repositories return collections of type Iterable<T>.

    On projects I've worked on in the past that use Spring, I've found that the need to operate on a Collection after retrieval has often dictated that Iterable<T> is used in the business layer rather than Collection<T> in order to select an Object T from the collection.

    All Collections are Iterable (that is the interfaces which extend the Collection interface, so not Map!), so using Iterable in the business layer is merely a case of referring to a Collection by its super type and still allows the use of for-each to iterate.

    If you need to manipulate the contents of a collection, a convenience method would allow you to populate a new Collection, so you can make use of contains(), remove(), etc with the original collection data.

    Alternatively, convenience methods are provided for this purpose by popular third party APIs such as Google Guava and Apache Commons.

    0 讨论(0)
  • 2021-01-30 01:32

    Many of the collection types existed before Iterable<T> (which was only introduced in 1.5) - there was little reason to add a constructor to accept Iterable<T> as well as Collection<T> but changing the existing constructor would have been a breaking change.

    Personally I would use Iterable<T> if that allows you to do everything you want it to. It's more flexible for callers, and in particular it lets you do relatively easy filtering/projection/etc using the Google Java Collections (and no doubt similar libraries).

    0 讨论(0)
提交回复
热议问题