在ArrayList 应用中有这样的代码:ArrayList a=new ArrayList();a.add(...);Iterator i=a.iterator();下面这句怎么也理解不了:Iterator i=a.iterator();Iterator 不是一个接口吗?返回一个接口有什么用啊,a.iterator()方法的作用是什么?
还有hasmore(),next()是怎么被实现的?请指教
还有hasmore(),next()是怎么被实现的?请指教
解决方案 »
- 《java就业培训教程》的一道题
- static 问题
- struts <data-sources> 配置 放在什么目录下 在线等!!!!!!
- java帮我分析下
- 该是高手出手的时候到啦~~~快来啊~~
- j2se帮忙差错!谢谢,公有函数点不出来!急
- 用ArrayList(假设list是一个ArrayList的实例)加上synchronized关键字,是不是也能达到Vector那样的线程安全的效果?
- 如何设置控件的位置呀----新手求救。
- 在tomcat4.0.3中的CLASSPATH怎样设置,我在环境变量里设置了,但没用,应该怎么办,给分给分!
- 小白求解 韩顺平老师教程里坦克大战的爆炸效果为什么是从第二个坦克爆炸才有
- 我有一套JSP源程序,想修改一下为我所用,但是有点麻烦
- 不知道这种问题有没有人会???请经验丰富的java高手进来帮忙看看!
i虽然是一个接口,但实际上当然是指向那个实现了Iterator的那个类。
while (i.hasMore())
Object elem = i.next;
public Iterator iterator() {
return new Itr();
} 并且有个内部类 Itr private class Itr implements Iterator {
/**
* Index of element to be returned by subsequent call to next.
*/
int cursor = 0; /**
* Index of element returned by most recent call to next or
* previous. Reset to -1 if this element is deleted by a call
* to remove.
*/
int lastRet = -1; /**
* The modCount value that the iterator believes that the backing
* List should have. If this expectation is violated, the iterator
* has detected concurrent modification.
*/
int expectedModCount = modCount; public boolean hasNext() {
return cursor != size();
} public Object next() {
checkForComodification();
try {
Object next = get(cursor);
lastRet = cursor++;
return next;
} catch(IndexOutOfBoundsException e) {
checkForComodification();
throw new NoSuchElementException();
}
} public void remove() {
if (lastRet == -1)
throw new IllegalStateException();
checkForComodification(); try {
AbstractList.this.remove(lastRet);
if (lastRet < cursor)
cursor--;
lastRet = -1;
expectedModCount = modCount;
} catch(IndexOutOfBoundsException e) {
throw new ConcurrentModificationException();
}
} final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
Iterator 是一个接口 ,但
a.iterator(); 返回的是一个Itr 对象,该对象实现了Iterator 接口接口指向一个实现了他的 对象,有什么问题么??
还是循序渐进比较好。
不知道接口的实现原理,看看源代码,
再看看设计模式(design pattern)中的iterator pattern.
相信看后你会明白的。
我一开始也和你一样,一头雾水!