java中面向接口编程之迭代器

“为什么说实现了Iterable接口的集合必须提供一个称为iterator的方法,该方法返回一个Iterator类型的对象。”

没有别的原因,原因只有一个,就是因为Iterable接口的定义如下:

复制代码
1 package java.lang;
2 
3 import java.util.Iterator;
4 
5 
6 public interface Iterable<T>
7 {
8         Iterator<T> iterator();
9 }
复制代码

 既然这么定义了,那么就必须这么实现。

---------------------------------------------the brilliant division line--------------------------------------------------------------------------------------

Collection接口定义如下:

复制代码
 1 public interface Collection<T> extends Iterable<T>
 2 {
 3         int size();
 4         boolean isEmpty();
 5         void clear();
 6         boolean contains();
 7         boolean add(T x);
 8         boolean remove(T x);
 9         java.util.Iterator<T> iterator();
10 }
复制代码

Iterable接口定义如下:

1 public interface Iterable<T>
2 {
3         Iterator<T> iterator();
4 }

Iterator接口定义如下:

1 public interface Iterator<E>
2 {
3         boolean hasNext();
4         E next();
5         void remove();
6 }

这三者的关系是:Collection接口扩展了(extends)Iterable接口,Iterable接口定义中只包含了一个返回类型为Iterator<T>的方法iterator,接口Iterator的定义是由hasNext、next、remove三个方法组成的。

查看Collection定义和Iterator定义可发现,Collection有remove方法,Iterator也有remove方法,那么问题出现了,二者的remove方法有何区别呢?我们更倾向于使用谁的remove方法呢?为什么?

待续。。。。。。。。。。。

猜你喜欢

转载自www.cnblogs.com/zhaodongdong/p/9088014.html
今日推荐