1 // IntList.java
2 package newlocal;
3
4 import java.util.Iterator;
5 import java.util.NoSuchElementException;
6 import java.util.function.Consumer;
7
8 /** 9 * IntList verwaltet ganze Zahlen als Liste. 10 * Beispielprogramm zur Programmiertechnik 1, Teil 5. 11 * @author H.Drachenfels 12 * @version 13.6.2023 13 */
14 public final class IntList implements Iterable<Integer> {
15
16 private Element head = null; // leere Liste
17
18 /** 19 * F&uuml;gt eine Zahl am Listenanfang ein. 20 * @param n die einzuf&uuml;gende Zahl 21 * @return die Liste 22 */
23 public IntList insert(int n) {
24 this.head = new Element(this.head, n);
25 return this;
26 }
27
28 /** 29 * Element speichert eine einzelne Zahl als Teil einer Liste. 30 * Beipiel f&uuml;r eine statisch eingebettete Klasse. 31 */
32 private static final class Element {
33 private final Element next;
34 private final int n;
35
36 private Element(Element e, int n) {
37 this.next = e;
38 this.n = n;
39 }
40 }
41
42 @Override
43 public Iterator<Integer> iterator() {
44 // Beispiel fuer eine anonyme lokale innere Klasse
45 return new Iterator<Integer>() {
46 private Element current = IntList.this.head;
47
48 @Override
49 public boolean hasNext() {
50 return this.current != null;
51 }
52
53 @Override
54 public Integer next() {
55 if (this.current == null) {
56 throw new NoSuchElementException();
57 }
58
59 Element e = this.current;
60 this.current = this.current.next;
61 return e.n; // Integer.valueOf(e.n);
62 }
63 };
64 }
65
66 @Override
67 public void forEach(Consumer<? super Integer> action) {
68 for (Element e = this.head; e != null; e = e.next) {
69 action.accept(e.n);
70 }
71 }
72 }
73