Creating your own Iterable structure for use with Iterator or for-each loop.

suggest change

To ensure that a collection works with an iterator or a for-each loop:

  1. The collection implements Iterable and provides iterator().
  2. Its iterator implements hasNext() and next(). The optional remove() operation may throw UnsupportedOperationException.

This generic singly linked list implements both pieces:

package org.algorithms.linkedlist;

import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.StringJoiner;

public class LinkedList<T> implements Iterable<T> {
    private Node<T> head;

    private static final class Node<T> {
        private final T data;
        private Node<T> next;

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

    public LinkedList(T data) {
        head = new Node<>(data);
    }

    @Override
    public Iterator<T> iterator() {
        return new LinkedListIterator();
    }

    private final class LinkedListIterator implements Iterator<T> {
        private Node<T> node = head;

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

        @Override
        public T next() {
            if (!hasNext()) {
                throw new NoSuchElementException();
            }
            T data = node.data;
            node = node.next;
            return data;
        }
    }

    public void add(T data) {
        Node<T> current = head;
        while (current.next != null) {
            current = current.next;
        }
        current.next = new Node<>(data);
    }

    public static void main(String[] args) {
        LinkedList<Integer> list = new LinkedList<>(1);
        list.add(2);
        list.add(4);
        list.add(3);

        System.out.println("using Iterator:");
        Iterator<Integer> iterator = list.iterator();
        StringJoiner iteratorValues = new StringJoiner(" ");
        while (iterator.hasNext()) {
            iteratorValues.add(iterator.next().toString());
        }
        System.out.println(iteratorValues);

        System.out.println("\nusing for-each:");
        StringJoiner forEachValues = new StringJoiner(" ");
        for (Integer data : list) {
            forEachValues.add(data.toString());
        }
        System.out.println(forEachValues);
    }
}
using Iterator:
1 2 4 3

using for-each:
1 2 4 3

The diamond operator (<>) lets the compiler infer the generic type arguments on the constructor.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents