Java 类型参数不在类型变量的范围内

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22650289/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 17:06:33  来源:igfitidea点击:

type argument is not within bounds of type-variable

javastack

提问by saqehi

Hi Stack Overflow community ^_^

嗨堆栈溢出社区^_^

Basically, I am working with Stacks and converting from Infix to Postfix equations. This is the error message showing on screen when I am trying to compile the Stack class:

基本上,我正在使用堆栈并将中缀转换为后缀方程。这是我尝试编译 Stack 类时在屏幕上显示的错误消息:

Stack.java:5: error: type argument T#1 is not within bounds of type-variable T#2
    private LinkedList<T> list;
                       ^
  where T#1,T#2 are type-variables:
    T#1 extends Object declared in class Stack
    T#2 extends Comparable<T#2> declared in class LinkedList

I am having real troubles trying to figure out this error but sadly I don't have a clue of what might be the problem. If I knew a little better I could have provided you with more info.

我在试图找出这个错误时遇到了真正的麻烦,但遗憾的是我不知道可能是什么问题。如果我知道得更好一点,我可以为您提供更多信息。

Thanks in advance for any comments and help!

在此先感谢您的任何意见和帮助!

Update: Here is my class...

更新:这是我的课...

package ListPkg; 

public class Stack<T> //    implements Comparable<Stack>>  
{ 
    private LinkedList<T> list; 

    public Stack()
    {
        this("list");
    }
    public Stack(String name)
    {
        list = new LinkedList(name);
    }
    public void push(T item)
    {
        list.insertAtFront(item);
    }
    public T pop()
    {
        list.removeFromFront();
    }
    public int lenghtIs()
    {
        return list.lengthIs();
    }
    public T peek()
    {
        return list.returnFirstNode();
    }
    public void print()
    {
        list.print();
    }
    public boolean isEmpty()
    {
        return list.isEmpty();
    }
}

回答by Sotirios Delimanolis

It seems you have a class LinkedListdeclared as

看来你有一个类LinkedList声明为

class LinkedList<T extends Comparable<T>> {...}

but you're trying to use it in a class Stackdeclared as

但是您试图在Stack声明为的类中使用它

class Stack<T> {
    private LinkedList<T> list;
    ...
}

The type variable Tdeclared in Stackis completely unrelated to the type variable Tin LinkedList. What's more, they are not compatible. LinkedListexpects a type that is a sub type of Comparable, but Stackis giving it a type argument that has no bounds. The compiler cannot allow this.

该类型变量T的声明Stack是完全无关的类型变量TLinkedList。更重要的是,它们不兼容。LinkedList期望一个类型是 的子类型Comparable,但是Stack给它一个没有边界的类型参数。编译器不允许这样做。

Add appropriate bounds to your Stackclass' type parameter

Stack类的类型参数添加适当的边界

class Stack<T extends Comparable<T>> {