Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do so many methods use Collection rather than Iterable?

Tags:

java

iterable

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?

like image 222
Svish Avatar asked May 11 '11 11:05

Svish


2 Answers

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.

like image 71
Peter Lawrey Avatar answered Oct 18 '22 08:10

Peter Lawrey


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.

like image 24
bestsss Avatar answered Oct 18 '22 09:10

bestsss