【问题标题】:How to implements Iterable如何实现可迭代
【发布时间】:2013-06-30 10:35:18
【问题描述】:

在我的程序中,我编写了自己的 LinkedList 类。还有一个实例,llist。

在foreach循环中使用如下,LinkedList需要实现Iterable吗?

for(Node node : llist) {
    System.out.print(node.getData() + " ");
}

以下是我的 LinkedList 类。请让我知道如何使其可迭代?

public class LinkedList implements Iterable {
    private Node head = null;
    private int length = 0;

    public LinkedList() {
        this.head = null;
        this.length = 0;
    }

    LinkedList (Node head) {
        this.head = head;
        this.length = 1;
    }

    LinkedList (LinkedList ll) {
        this.head = ll.getHead();
        this.length = ll.getLength();
    }

    public void appendToTail(int d) {
        ...
    }

    public void appendToTail(Node node) {
        ...
    }

    public void deleteOne(int d) {
        ...
    }

    public void deleteAll(int d){
        ...
    }

    public void display() {
        ...
    }

    public Node getHead() {
        return head;
    }
    public void setHead(Node head) {
        this.head = head;
    }
    public int getLength() {
        return length;
    }
    public void setLength(int length) {
        this.length = length;
    }

    public boolean isEmpty() {
        if(this.length == 0)
            return true;
        return false;
    }
}

【问题讨论】:

  • JDK是开源的,源码自带。只需查看标准的 LinkedList 实现即可获得示例。
  • 但首先您需要阅读有关如何实现接口的一般主题的基本教程。你可以找到一个像样的here。你不会后悔这样做的。

标签: java foreach iterator iterable implements


【解决方案1】:

实现Iterable接口的唯一方法iterator()

您需要在此方法中返回Iterator 的实例。通常,这是通过创建一个实现 Iterator 的内部类并通过创建该内部类的实例并返回它来实现 iterator 来完成的。

【讨论】:

  • 您能具体说明一下吗?谢谢!
  • 能否请您指定您希望我指定的内容?
  • 能否实现iterator()?
  • 我对接口和实现不是很熟悉。非常感谢您的帮助!
猜你喜欢
  • 2013-11-02
  • 1970-01-01
  • 2015-01-22
  • 2016-01-23
  • 2016-06-15
  • 1970-01-01
  • 1970-01-01
  • 2020-10-02
  • 2016-02-26
相关资源
最近更新 更多