繁体   English   中英

Java泛型绑定不匹配错误

[英]Java Generics Bound Mismatch Error

我正在用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 编译此代码时,我在初始化节点时遇到错误。

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>

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

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

    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在内部类中也可见。

谢谢,

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM