我正在使用Java中的Generics实现LinkedList Stack实现.我收到一个错误,想知道为什么我得到它,因为我不清楚.
错误:
Error: /Path/To/Code/Java/MyLinkedList.java:64: incompatible types
found: Item
required: Item
Run Code Online (Sandbox Code Playgroud)
代码(它出现在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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
您已Item在顶级类和内部类中声明为类型参数.因此,Itemin 与之MyLinkedList<Item>不同ListIterator<Item>,因此是不相容的.你可以让你的ListIterator类非泛型:
private class ListIterator implements Iterator<Item>
Run Code Online (Sandbox Code Playgroud)
......你应该没事.
另外,我建议将类型参数更改为Item单个字母E,以避免让它与某些实际类混淆.按照惯例,类型参数应该是单个大写字母.
| 归档时间: |
|
| 查看次数: |
667 次 |
| 最近记录: |