Why is there a method iterator() on java.util.Coll

2020-07-02 09:23发布

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?

4条回答
小情绪 Triste *
2楼-- · 2020-07-02 10:03

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.

查看更多
Fickle 薄情
3楼-- · 2020-07-02 10:08

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.

查看更多
倾城 Initia
4楼-- · 2020-07-02 10:20

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.

查看更多
够拽才男人
5楼-- · 2020-07-02 10:20

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.

查看更多
登录 后发表回答