使用泛型的不兼容类型

时间:2013-11-20 06:53:22

标签: java generics

我正在使用Java中的Generics实现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;
       }
   }    
}

1 个答案:

答案 0 :(得分:6)

您已在顶级类和内部类中声明Item作为类型参数。因此,Item中的MyLinkedList<Item>ListIterator<Item>中的ListIterator不同,因此不兼容。您可以将private class ListIterator implements Iterator<Item> 类设为非泛型:

Item

......你应该没事。

另外,我建议将类型参数E更改为单个字母{{1}},以避免让它与某些实际类混淆。按照惯例,类型参数应该是单个大写字母。