Ich implementiere eine LinkedList-Stack-Implementierung mit Generics in Java als Übung. Ich erhalte einen Fehler und möchte wissen, warum ich ihn erhalte, da er mir nicht klar ist.
Der Fehler:
Fehler: /Pfad/Zu/Code/Java/MyLinkedList.java:64: inkompatible Typen
gefunden: Item
erforderlich: Item
Der Code (es tritt im Next()-Methode des ListIterator gegen Ende auf. Es gibt Kommentare daneben.):
import java.util.Iterator;
import java.util.NoSuchElementException;
public class MyLinkedList implements Iterable {
private Node first;
private int N; //Größe
private class Node {
private Node next;
private Item item;
private Node(Item item, Node next) {
this.item = item;
this.next = next;
}
}
public int size() {
return N;
}
public boolean isEmpty() {
return this.first == null;
}
public void push(Item data) {
Node oldfirst = this.first;
this.first = new Node(data, first);
this.N++;
}
public Item pop() {
if (isEmpty()) throw new NoSuchElementException("Unterlauf");
Item item = this.first.item;
this.first = this.first.next;
this.N--;
return item;
}
public Item peek() {
if (isEmpty()) throw new NoSuchElementException("Unterlauf");
return first.item;
}
public String toString() {
StringBuilder list = new StringBuilder();
for ( Item item : this) {
list.append(item + " ");
}
return list.toString();
}
public Iterator iterator() { return new ListIterator(); }
private class ListIterator implements Iterator {
private Node current = first;
public boolean hasNext() { return current != null; }
public void remove() { System.out.println("Kann das nicht tun, Alter"); }
public Item next() {
if (!hasNext()) throw new NoSuchElementException();
//Die betreffende Zeile:
Item item = current.item;
//Ich habe es geschafft, es zu beheben, wenn ich: Item item = (Item) current.item; schreibe
//Warum ist das notwendig?
current = current.next;
return item;
}
}
}