为什么迭代器方法同时存在于Iterable和Collection接口中? [英] Why is the iterator method present in both Iterable and Collection interfaces?
问题描述
Iterable
接口具有以下方法:
Iterator<T> iterator();
Collection
界面扩展了 Iterable
,并且还声明了相同的方法。
The Collection
interface extends Iterable
, and it also declares the same method.
我怀疑在设计Java集合时需要两次将相同的方法声明放入两次吗?
I am doubtful what was the need of putting the same method declaration twice while designing Java collections?
推荐答案
主要原因是Java 5。
The main reason is Java 5.
java.util.Collection
与自Java 1.2起就存在它的 iterator()
方法和 java.util.Iterator
。
java.util.Collection
with its iterator()
method and java.util.Iterator
exist since Java 1.2.
当他们想在Java 5中引入增强的for循环(一个 for(String s:...){}
时,他们需要一个从未实现 java.util.Collection
的类中创建 java.util.Iterator
的方法。引入了一个新接口 java.lang.Iterable
,该接口可以由所有想要支持增强的for循环的类实现。
When they wanted to introduce the enhanced for loop in Java 5 (the one for (String s: ...) {}
, they needed a way to create a java.util.Iterator
from classes that do not implement java.util.Collection
. The decision was made to introduce a new interface java.lang.Iterable
that can be implemented by all classes that want to support the enhanced for loop.
为了使现有的 java.util.Collection
及其所有后代接口和类与增强的for循环兼容,他们制作了 java .util.Collection
扩展 java.lang .Iterable
。
To make the existing java.util.Collection
and all it's descendent interfaces and classes compatible with the enhanced for loop, they made java.util.Collection
extend java.lang.Iterable
.
因此,两个接口都有一个方法 iterator()
- java.util.Collection
,因为它是第一个诞生的, java.lang.Iterable
用于支持增强的for循环。
Therefore both interfaces have a method iterator()
- java.util.Collection
because it was the "first born", java.lang.Iterable
for supporting the enhanced for loop.
这篇关于为什么迭代器方法同时存在于Iterable和Collection接口中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!