首頁  >  問答  >  主體

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()方法,为什么可以最后一步这样调用呢?

天蓬老师天蓬老师2712 天前685

全部回覆(3)我來回復

  • 高洛峰

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

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

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

    其中ItrAbstractList的内部类,实现了Iterator介面。

    回覆
    0
  • 迷茫

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

    ArrayList不是有嗎? ?

    回覆
    0
  • 天蓬老师

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

    這個Iterator應該是ArrayList的內部類別吧,如果ArrayList中找不到的話它的基底類別中應該有,不同的集合類別Iterator應該也各不相同,你可以自己看看原始碼。

    回覆
    0
  • 取消回覆