1 // IntList.java
2 package local;
3
4 import java.util.Iterator;
5 import java.util.NoSuchElementException;
6
7 /** 8 * IntList verwaltet ganze Zahlen als Liste. 9 * Beispielprogramm zur Programmiertechnik 1, Teil 5. 10 * @author H.Drachenfels 11 * @version 13.6.2023 12 */
13 public final class IntList implements Iterable<Integer> {
14
15 private Element head = null; // leere Liste
16
17 /** 18 * F&uuml;gt eine Zahl am Listenanfang ein. 19 * @param n die einzuf&uuml;gende Zahl 20 * @return die Liste 21 */
22 public IntList insert(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&uuml;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(Element e, int n) {
36 this.next = e;
37 this.n = n;
38 }
39 }
40
41 @Override
42 public Iterator<Integer> iterator() {
43 // Beispiel fuer eine anonyme lokale Klasse
44 return new Iterator<Integer>() {
45 private Element current = IntList.this.head;
46
47 @Override
48 public boolean hasNext() {
49 return this.current != null;
50 }
51
52 @Override
53 public Integer next() {
54 if (this.current == null) {
55 throw new NoSuchElementException();
56 }
57
58 Element e = this.current;
59 this.current = this.current.next;
60 return Integer.valueOf(e.n);
61 }
62 };
63 }
64 }
65