[英]Incompatible types using generics
我正在實踐中使用Java中的泛型來實現LinkedList Stack實現。 我遇到了錯誤,並且想知道為什么會得到它,因為我不清楚。
錯誤:
Error: /Path/To/Code/Java/MyLinkedList.java:64: incompatible types
found: Item
required: Item
代碼(它出現在ListIterator的Next()方法的最后。它帶有注釋。):
import java.util.Iterator;
import java.util.NoSuchElementException;
public class MyLinkedList<Item> implements Iterable<Item> {
private Node first;
private int N; //size
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("Underflow");
Item item = this.first.item;
this.first = this.first.next;
this.N--;
return item;
}
public Item peek() {
if (isEmpty()) throw new NoSuchElementException("Underflow");
return first.item;
}
public String toString() {
StringBuilder list = new StringBuilder();
for ( Item item : this) {
list.append(item + " ");
}
return list.toString();
}
public Iterator<Item> iterator() { return new ListIterator(); }
private class ListIterator<Item> implements Iterator<Item> {
private Node current = first;
public boolean hasNext() { return current != null; }
public void remove() { System.out.println("Can't do dis, nigga"); }
public Item next() {
if (!hasNext()) throw new NoSuchElementException();
//The line in question:
Item item = current.item;
//I managed to fix it if I do: Item item = (Item) current.item;
//Why is that necessary?
current = current.next;
return item;
}
}
}
您已經在頂級類和內部類中將Item
聲明為類型參數。 所以, Item
在MyLinkedList<Item>
是在從不同ListIterator<Item>
因此是不兼容的。 您可以將ListIterator
類ListIterator
非通用類:
private class ListIterator implements Iterator<Item>
...你應該沒事的。
另外,我建議將類型參數Item
更改為一些單個字母,例如E
,以避免將其與某些實際類混淆。 按照約定,類型參數應為單個大寫字母。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.