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

后端 未结 9 1622
独厮守ぢ
独厮守ぢ 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:32

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

    Personally I would use Iterable 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).

提交回复
热议问题