Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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;
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
150 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...