【问题标题】:Where is the iterator() method in LinkedList class in Java?Java中LinkedList类中的iterator()方法在哪里?
【发布时间】:2018-07-19 15:21:50
【问题描述】:
package Practice;

import java.util.LinkedList;
import java.util.Iterator;

public class CollectionTest {

public static void main(String[] args) {

    LinkedList<String> c = new LinkedList<String>();
    c.add("Hello");
    c.add("World");
    c.add("java");

    Iterator<String> it = c.iterator();
    while (it.hasNext()) {
        System.out.println(it.next());
    }

}
}

我的问题: 由于 Collection 扩展了 Iterable 接口,所以它具有 Iterable 中定义的抽象方法 iterator()。所以,LinkedList 是一个具体的类,它实现了扩展 Collection 接口的 List 接口,应该有一个 iterator() 方法的重写版本,我猜......

我看到了SUN公司的ArrayList类源码,里面有一个实现Iterator接口的内部类“Itr”,通过调用ArrayList类里面的“public Iterator iterator()”方法,会返回一个“新的 Itr()”。

但我的困惑是我在 LinkedList 中找不到 iterator() 方法。我只在 LinkedList 类中找到了一个“descendingIterator()”方法,这不是我想要的……但是 LinkedList 中 iterator() 方法的覆盖版本到底在哪里?在我的代码中,我创建了一个 LinkedList 对象,并使用该对象来调用它的 iterator() 方法,并且它可以工作。但是既然 LinkedList 中没有重写的 interator() 方法,为什么它可以工作呢?它是否在其超类(如 List)中调用 interator() 方法?收藏?但是这些都是interator()没有具体方法体的接口......还有为什么当迭代器引用“it”调用hasNext和next方法时它仍然有效?

对不起,我冗长的问题陈述......我希望这能让你理解我的困惑......非常感谢你的帮助谢谢!

【问题讨论】:

  • 来自public abstract class AbstractSequentialList&lt;E&gt; extends AbstractList&lt;E&gt;。在 Eclipse 中,您可以右键单击该方法并选择“Open Declaration”,它会显示该方法的位置。
  • 非常感谢你们!!!我现在清楚了。
  • 类似问题已解决here

标签: java linked-list iterator iterable


【解决方案1】:

LinkedList 扩展了一个抽象的AbstractSequentialList 类,它定义了方法getsetiteratoraddremove。因为AbstractSequentialList 扩展了一个抽象的AbstractList 类。

public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, java.io.Serializable
{...}

【讨论】:

    【解决方案2】:

    在LinkedList的父类中:AbstractSequentialList

    【讨论】:

      【解决方案3】:

      至于

      LinkedList<E> extends AbstractSequentialList<E>
      

      此方法在 AbstractSequentialList 中的实现。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-05-27
        • 2016-03-02
        • 2021-04-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-30
        • 2013-07-21
        相关资源
        最近更新 更多