implementing iterator for linked list java 1

implementing iterator for linked list java

public class BasicLinkedList implements Iterable {
    public int size;

    private class Node {
        private T data;
        private Node next;

        private Node(T data) {
            this.data = data;
            next = null;
        }
    }

    private Node head;
    private Node tail;

    public BasicLinkedList() {
        head = tail = null;
    }
//Add, remove method 

public Iterator iterator() {
        return new Iterator() {

            Node current = head;

            @Override
            public boolean hasNext() {
                return current != null;
            }

            @Override
            public T next() {
                if(hasNext()){
                    T data = current.data;
                    current = current.next;
                    return data;
                }
                return null;
            }

            @Override
            public void remove(){
                throw new UnsupportedOperationException("Remove not implemented.");
            }

        };

Here is what the above code is Doing:
1. We create a new class called Iterator that implements the Iterator interface.
2. We create a new Node called current and set it equal to the head of the list.
3. We override the hasNext() method to return true if the current node is not null.
4. We override the next() method to return the data of the current node and then set the current node to the next node.
5. We override the remove() method to throw an UnsupportedOperationException.
6. We return the new Iterator object.

Similar Posts