如何实现Iterable

时间:2013-07-02 21:25:27

标签: java foreach iterator iterable implements

在我的程序中,我编写了自己的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;
    }
}

1 个答案:

答案 0 :(得分:2)

实施Iterable界面的唯一方法iterator()

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

相关问题