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

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

    Use the most general interface that you can. Since all you're going to do is iterate, then I would say Iterable is the way to go (since it allows lazy iterators, etc.). You don't care where the iterator is coming from, so don't restrict it more than you have to.

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

    You're correct, as it's considered good practice to ask for the most general form of what you need.

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

    An Iterable produces Iterator objects. An Iterator object, by definition, iterates. Notice, that the Iterator interface makes no promise as to how many times next() can be called before hasNext() returns false. An Iterator could possibly iterate over Integer.MAX_VALUE + 1 values before its hasNext() method returns false.

    However, a Collection is a special form of Iterable. Because a Collection cannot have more than Integer.MAX_VALUE elements (by virtue of the size() method), it is naturally presumed that its Iterator objects will not iterate over this many elements.

    Therefore, by accepting a Collection rather than an Iterable, your class can have some guarantee over how many elements are being passed in. This is especially desirable if your class is itself a Collection.

    Just my two cents...

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

    Some constructors, e.g. ArrayList(Collection c), use the toArray() method of Collection for efficiency.

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

    According to the principle of least surprise, you should emulate the Java collection pattern and take a Collection constructor arg. It will make the people who come after you slightly less puzzled.

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

    If you go for Collection, then your class can be initialised from a collection only, if you go for Iterable, then you can initialise from either collection or iterable.

    As the effort and performance for both is going to be the same, it makes total sense to accept Iterable in the constructor.

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