-1

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;
    }
}
Elazar
  • 20,415
  • 4
  • 46
  • 67
Zoe
  • 997
  • 4
  • 10
  • 19
  • 2
    The JDK is open-source, and the source comes with it. Just look at the standard LinkedList implementation to have an example. – JB Nizet Jul 02 '13 at 21:31
  • But first you'll want to read a basic tutorial on the general subject of how to implement interfaces. You can find a decent one [**here**](http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html). You won't regret doing this. – Hovercraft Full Of Eels Jul 02 '13 at 21:46

1 Answers1

2

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.

rgettman
  • 176,041
  • 30
  • 275
  • 357