With C# I grew to love the IEnumerable<T>
interface. There are a lot of cases where that's all you want to give out and take in. In addition it's useful in the .Net library. You have for example a constructor on the List<T>
class which takes an IEnumerable<T>
.
I have to work with Java at the moment, and I naturally wanted to use the equivalent Iterable<T>
interface. However, it doesn't really seem like I can use it anywhere. Everything seems to be using the extended Collection<T>
interface instead. Why is this?
As an example, you have the ArrayList<T>
constructor which takes a Collection<T>
:
Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator.
Why not just take an Iterable<T>
instead?
Iterable was only added in Java 5. This means older methods (most of them) use collections. Even newer methods which could take Iterable haven't used it. :(
I think the problem is that most Iterable are Collections.
As an example, you have the ArrayList constructor which takes a Collection
Having predictable size is good, esp. for an ArrayList (it does use toArray() to build its underlying Object[])
Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator.
Lovely sun were lazy to update the docs again, it doesn't use iterator at all; Actually myself I almost never read the docs since they often tend to be either mislead or just plain wrong.
Also you can easily fit an Iterable to a Collection by subclassing AbstractCollection (which lacks only size() and iterator() readily implemented)
Iterable was introduced mostly to conform foreach
construct.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With