日期:2014-05-20  浏览次数:20667 次

指教Iterator接口的问题
我在一本书看到这样的代码:
                    ArrayList   al=new   ArrayList();    
     Iterator   itr=al.iterator();
Iterator是一个接口,不是说了接口是不能定义对象的吗?怎么这里又定义了itr这 个Iterator对象??
很多人认为al.iterator()返回的是Iterator的一个实现类的实例。但我
在java文栏中没有查到ArrayList实现了Iterator接口?又何谈al.iterator()返回的是Iterator的一个实现类的实例呢??


------解决方案--------------------
Iterator 是Interface, Interface 不能用来new 一个对象,但是可以用来指定新建对象的类型。
ArrayList 的iterator() 是method/function,这个继承没有关系。

------解决方案--------------------
把分给我啊,我给你解释。嘿嘿 (没分下载东东了)
你看文档里的这段话:
Methods inherited from class java.util.AbstractList
equals, hashCode, iterator, listIterator, listIterator, subList
这个iterator方法是继承自java.util.AbstractList 这里的,所以ArrayList里也有这个方法的
看看他的返回类型
iterator
public Iterator <E> iterator()
Returns an iterator over the elements in this list in proper sequence.
This implementation returns a straightforward implementation of the iterator interface, relying on the backing list 's size(), get(int), and remove(int) methods.

Note that the iterator returned by this method will throw an UnsupportedOperationException in response to its remove method unless the list 's remove(int) method is overridden.

This implementation can be made to throw runtime exceptions in the face of concurrent modification, as described in the specification for the (protected) modCount field.


Specified by:
iterator in interface Iterable <E>
Specified by:
iterator in interface Collection <E>
Specified by:
iterator in interface List <E>
Specified by:
iterator in class AbstractCollection <E>
Returns:
an iterator over the elements in this list in proper sequence.
See Also:
modCount
就知道了,是返回的Iterator 这就是他们的关系啦!!

------解决方案--------------------
接口的确不能实类化对象也就是NEW),但可以定义一个对象的类型
------解决方案--------------------
Iterator itr=al.iterator();只是声名了一个Iterator类型的引用itr.并不是实例化一个Iterator对象(Iterator itr=new iterator();//这个不行)
事实上,只要一个类A实现了一个接口B,那么可以把A的一个实例化对象c的引用附给B.
------------------------------
public iterface B{...}
class A implements B{..}
A c = new A();
B b = c ;
----------------------------------------