Creating your own Iterable structure for use with Iterator or for-each loop.
suggest changeTo ensure that a collection works with an iterator or a for-each loop:
- The collection implements
Iterableand providesiterator(). - Its iterator implements
hasNext()andnext(). The optionalremove()operation may throwUnsupportedOperationException.
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.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents