指教Iterator接口的问题

hyip 2007-05-17 07:10:56
我在一本书看到这样的代码:
ArrayList al=new ArrayList();
     Iterator itr=al.iterator();
Iterator是一个接口,不是说了接口是不能定义对象的吗?怎么这里又定义了itr这 个Iterator对象??
很多人认为al.iterator()返回的是Iterator的一个实现类的实例。但我
在java文栏中没有查到ArrayList实现了Iterator接口?又何谈al.iterator()返回的是Iterator的一个实现类的实例呢??
...全文
455 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
jackshen016 2007-08-08
  • 打赏
  • 举报
回复
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 ;
----------------------------------------
viecen1314 2007-08-06
  • 打赏
  • 举报
回复
接口的确不能实类化对象也就是NEW),但可以定义一个对象的类型
bruni 2007-05-18
  • 打赏
  • 举报
回复
但是返回的是Iterator类型的,说明al.iterator()返回的是Iterator的一个实现类的实例.也就是说ArrayList是Iterator的实现类,
=> 完全错误!!!
难道我返回Exception类型的实例就一定是Exception的实现类?荒谬!
继承是什么概念搞清楚先!
thinker87 2007-05-17
  • 打赏
  • 举报
回复
把分给我啊,我给你解释。嘿嘿 (没分下载东东了)
你看文档里的这段话:
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 这就是他们的关系啦!!
hyip 2007-05-17
  • 打赏
  • 举报
回复
但是返回的是Iterator类型的,说明al.iterator()返回的是Iterator的一个实现类的实例.也就是说ArrayList是Iterator的实现类,但查Jdk文档找不到它们有这种关系??
这样又如何解释啊?
hyip 2007-05-17
  • 打赏
  • 举报
回复
但是返回的是Iterator类型的,说明al.iterator()返回的是Iterator的一个实现类的实例.也就是说ArrayList是Iterator的实现类,但查Jdk文档找不到它们有这种关系??
bruni 2007-05-17
  • 打赏
  • 举报
回复
Iterator 是Interface, Interface 不能用来new 一个对象,但是可以用来指定新建对象的类型。
ArrayList 的iterator() 是method/function,这个继承没有关系。

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧