在ArrayList 应用中有这样的代码:ArrayList a=new ArrayList();a.add(...);Iterator i=a.iterator();下面这句怎么也理解不了:Iterator i=a.iterator();Iterator 不是一个接口吗?返回一个接口有什么用啊,a.iterator()方法的作用是什么?
还有hasmore(),next()是怎么被实现的?请指教

解决方案 »

  1.   

    ArrayList内部有一个实现了Iterator 接口的类,a.iterator就是返回它内部类的一个实例对于你的程序来说,不关心它的类是在哪里,只需要知道它实现了Iterator就可以了
    i虽然是一个接口,但实际上当然是指向那个实现了Iterator的那个类。
      

  2.   

    a.iterator();返回的是一个实现了iterator接口的类
      

  3.   

    接口是一个类型,相当于一个父类型(supertype),可以用一个接口引用一个实现了此接口的类的实例。这样只能用接口提供的方法来访问此对象,可以限制访问,隐藏具体实现。
      

  4.   

    知道iterator是做什么的,怎么用就是了
      

  5.   

    看看设计模式, 会对理解这个有帮助, iterator模式
      

  6.   

    Iterator i=a.iterator();
    while (i.hasMore())
         Object elem = i.next;
      

  7.   

    ArrayList extends AbstractListAbstractList 内部 有个方法
        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();
    }
        }
      

  8.   

    Iterator 不是一个接口吗?返回一个接口有什么用啊,...
    Iterator 是一个接口 ,但
    a.iterator(); 返回的是一个Itr 对象,该对象实现了Iterator 接口接口指向一个实现了他的 对象,有什么问题么??
      

  9.   

    呵呵....兄弟看到你的问题让我稍稍有点自信,这鬼java名堂真多让人学半天还入不了门
      

  10.   

    楼主有些急于求成吧?连接口是怎么回事都没搞清楚就要学ArrayList,Iterator?
    还是循序渐进比较好。
      

  11.   

    迭代器,我建议兄弟看一下Thinking in java 里面有很好的解释的
      

  12.   

    不知道返回一个接口有什么用?看一看thinking in java中的多态性。
    不知道接口的实现原理,看看源代码,
    再看看设计模式(design pattern)中的iterator pattern.
    相信看后你会明白的。
    我一开始也和你一样,一头雾水!