search

Home  >  Q&A  >  body text

java - 如图代码,Collection 类中的iterator()是抽象方法,为什么可以调用?

        Collection    c1 =new ArrayList();
        c1.add("hello");
        c1.add(1);
        Collection    c2 =new ArrayList();
        c2.add(new Student() );
        c2.addAll(c1);
        c2.add("我");
        Iterator it = c2.iterator();

Collection 与List 还有ArrayList都没有重写iterator()方法,为什么可以最后一步这样调用呢?

天蓬老师天蓬老师2802 days ago741

reply all(3)I'll reply

  • 高洛峰

    高洛峰2017-04-18 10:49:56

    ArrayList继承自AbstractList类, AbstractList类重写了List接口的iterator()Method:

    public Iterator<E> iterator() {
        return new Itr();
    }

    Which ItrAbstractList的内部类,实现了Iteratorinterface.

    reply
    0
  • 迷茫

    迷茫2017-04-18 10:49:56

    Isn’t there ArrayList? ?

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-18 10:49:56

    This Iterator should be the internal class of ArrayList. If it cannot be found in ArrayList, it should be in its base class. Iterators should be different for different collection classes. You can look at the source code yourself.

    reply
    0
  • Cancelreply