1 // IntList.java
2 package nested;
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 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 * Der heimliche Paramter this verweist auf das Objekt des Aufrufs. 19 * @param n die einzufügende Zahl 20 * @return die Liste 21 */
22 public IntList insert(/* final IntList this, */ int n) {
23 this.head = new Element(this.head, n);
24 return this;
25 }
26
27 /** 28 * Element speichert eine einzelne Zahl als Teil einer Liste. 29 * Beipiel für eine statisch eingebettete Klasse. 30 */
31 private static final class Element {
32 private final Element next;
33 private final int n;
34
35 private Element(/* final Element this, */ Element e, int n) {
36 this.next = e;
37 this.n = n;
38 }
39 }
40
41 /** 42 * Iterator speichert den aktuellen Zustand einer Listeniteration. 43 * Beipiel für eine innere Klasse. 44 */
45 public final class Iterator {
46 // private IntList IntList.this;
47 private Element current = IntList.this.head;
48
49 /** 50 * prüt, ob das Listenende erreicht ist. 51 * Der heimliche Paramter this verweist auf das Objekt des Aufrufs. 52 * @return false, wenn das Listenende erreicht ist, sonst true. 53 */
54 public boolean hasNext(/* final Iterator this */) {
55 return this.current != null;
56 }
57
58 /** 59 * liefert die aktuelle Zahl und iteriert zum nächsten Jahr. 60 * Aufruf am Listenende liefert NoSuchElementException. 61 * Der heimliche Paramter this verweist auf das Objekt des Aufrufs. 62 * @return die aktuelle Zahl 63 */
64 public int next(/* final Iterator this */) {
65 if (this.current == null) {
66 throw new NoSuchElementException();
67 }
68
69 Element e = this.current;
70 this.current = this.current.next;
71 return e.n;
72 }
73 }
74 }
75