Java泛型绑定不匹配错误

时间:2013-01-27 07:38:20

标签: java generics

我正在用Java编写通用链表实现。代码是

public class LinkedList<T> {
    private Node<T> top;
    private int no_of_items;

    private class Node<T extends Comparable<? super T>> {
        T data;
        Node<T> next;
    }

    public LinkedList() {
        top = null;
    }

    public boolean isEmpty() {
        return (top == null);
    }

    public void insert(T item) {
        Node<T> node = new Node<T>();
        node.data = item;
        node.next = top;
        if(isEmpty()) {
            top = node;
        } else {
            Node<T> n = top; 
            while(n.next != null) {
                n = n.next;
            }
            n.next = node;
        }
        no_of_items++;

    }
}

我想要的是T应为Comparable。在编译此代码时,我在初始化Node时遇到错误。

Bound Mismatch the type T is not a valid substitute for the bounded parameter <T extends Comparable<? super T>> of the type LinkedList<T>.Node<T>

我无法弄清楚这里有什么问题。

1 个答案:

答案 0 :(得分:1)

我自己解决了这个错误。正确的代码是

    public class LinkedList<T extends Comparable<? super T>> {
private Node top;
private int no_of_items;

private class Node {
    T data;
    Node next;
}

public LinkedList() {
    top = null;
}

public boolean isEmpty() {
    return (top == null);
}

public void insert(T item) {
    Node node = new Node();
    node.data = item;
    node.next = top;
    if(isEmpty()) {
        top = node;
    } else {
        Node n = top; 
        while(n.next != null) {
            n = n.next;
        }
        n.next = node;
    }
    no_of_items++;

}
    }

答案在于,当我们在顶级类中使用泛型类型T并且我们具有非静态内部类时,同样的T在内部类中也是可见的。

谢谢,