1 // IntList.java
2 package staticnested;
3
4 import java.util.NoSuchElementException;
5
6 /** 7 * IntList verwaltet ganze Zahlen als Liste. 8 * Beispielprogramm zur Programmiertechnik 1, Teil 4. 9 * @author H.Drachenfels 10 * @version 22.12.2021 Variante mit statisch eingebetteter Iterator-Klasse 11 */
12 public final class IntList {
13
14 private Element head = null; // leere Liste
15
16 /** 17 * Fügt eine Zahl am Listenanfang ein. 18 * @param n die einzufügende Zahl 19 * @return die Liste 20 */
21 public IntList insert(int n) {
22 this.head = new Element(this.head, n);
23 return this;
24 }
25
26 /** 27 * Element speichert eine einzelne Zahl als Teil einer Liste. 28 * Beipiel für eine statisch eingebettete Klasse. 29 */
30 private static final class Element {
31 private final Element next;
32 private final int n;
33
34 private Element(Element e, int n) {
35 this.next = e;
36 this.n = n;
37 }
38 }
39
40 /** 41 * Iterator speichert den aktuellen Zustand einer Listeniteration. 42 * Beipiel für eine innere Klasse, 43 * hier mit einer statisch eingebetteten Klasse nachgebildet. 44 */
45 public static final class Iterator {
46 private final IntList list; // ersetzt IntList.this
47 private Element current;
48
49 /** 50 * Baut einen Iterator für eine Liste. 51 * @param list die Liste, über die iteriert werden soll 52 */
53 public Iterator(IntList list) {
54 this.list = list;
55 this.current = this.list.head;
56 }
57
58 /** 59 * prüt, ob das Listenende erreicht ist. 60 * @return false, wenn das Listenende erreicht ist, sonst true. 61 */
62 public boolean hasNext() {
63 return this.current != null;
64 }
65
66 /** 67 * liefert die aktuelle Zahl und iteriert zum nächsten Jahr. 68 * Aufruf am Listenende liefert NoSuchElementException. 69 * @return die aktuelle Zahl 70 */
71 public int next() {
72 if (this.current == null) {
73 throw new NoSuchElementException();
74 }
75
76 Element e = this.current;
77 this.current = this.current.next;
78 return e.n;
79 }
80 }
81 }
82