How to implements Iterable

2019-09-20 08:50发布

问题:

In my program, I write my own LinkedList class. And an instance, llist.

To use it in foreach loop as following, LinkedList needs to implement Iterable?

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

Here following is my LinkedList class. Please let me know how can I make it Iterable?

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:

Implement the only method of the Iterable interface, iterator().

You will need to return an instance of Iterator in this method. Typically this is done by creating an inner class that implements Iterator, and implementing iterator by creating an instance of that inner class and returning it.