views:

246

answers:

4

Why is there the method iterator() defined on the interface java.util.Collection when it already extends java.util.Iterable which has this very method defined.

I'm thinking some sort of backward compatability or an opportunity to write some JavaDoc on the method at the collection level.

Any other ideas?

+10  A: 

Backwards compatibility. Iterable was not introducted until 1.5 with the for(Object o : iterable) construct. Previously, all collections had to provide a means to iterate them.

Matt
iterator() doesn't just exist for backwards compatibility; It is often useful to have a handle to the Iterator directly.
Adamski
@Adamski, Dan is asking why is the method declared both on Collection and Iterable, when Collection extends Iterable. Your point seems to be addressing "why is there a method .iterator(), period?" which no one is asking.
matt b
Yeah - sorry; I realised that and trashed my answer!
Adamski
I also believe the foreach loop (Object o:Iterable) is rewritten by the compiler to use the iterator.No iterator means no foreach:)
extraneon
I'm a new user to stackoverflow so excuse me if this is a silly point - but why is it that an answer that has been deemed incorrect is the highest voted answer on this thread?
Dan
@Dan Why do you say this answer is incorrect? It seems correct. Adamski changed his mind .. ! :-)
KLE
@Dan this answer is correct. Sometimes you need to look at the API from a historical perspective to understand why certain things exist the way they do.
matt b
Yeah I changed my mind ... Well I reread the question ... I was in too much of a hurry to get the points!
Adamski
This answer is actually incorrect. The declaration in `Collection` is not necessary for either source or binary compatibility.
Tom Hawtin - tackline
+5  A: 

I suspect it was just to avoid the appearance of removing a method from a documentation point of view. Although javadoc is nice it would be difficult to notice/appreicate a method being moved from one interface to a super-interface.

Note the same was done with Closeable, also introduced in 1.5.

As far as I am aware there would have been no binary compatability issues with removing the method from the Collection class.

Mike Q
Indeed, there isn't any source compatibility issue either. (`Collection` interface, btw). I believe you would need a meta-linguistic facility, such as reflection, to tell the difference at runtime.
Tom Hawtin - tackline
+3  A: 

Iterable was introduced in 1.5. Since it was part of Collection from before 1.5 that they probably just didn't remove it. And as the other contributor pointed out, it does have better JavaDoc.

Andrew Mellinger
+1  A: 

I have been doing some more investigation on this and have found that the equals() and hashcode() methods are also overwritten.

Clearly the only reason for this can be to add the javadoc - maybe this is why iterator() was also overwritten.

Dan