3

我有一个扩展 LinkedList 类的类。这是代码的摘录:

class SortedList<Integer> extends LinkedList<Integer> {
      int intMethod(Integer integerObject){
          return integerObject;
      }
}

预计这将返回自动拆箱的 int 值。但是由于某种原因,编译器会抛出一个错误,指出类型不兼容,并且所需的类型是 int,而找到的类型是 Integer。这在不同的课程中非常有效!是什么赋予了?:(

4

2 回答 2

10

这是因为你有<Integer>after SortedList

通常你使用T类型参数:class SortedList<T>,但你使用Integer了。也就是说,您创建了Integer一个类型参数(它隐藏了java.lang.Integer)。

你的班级,就目前而言,相当于

class SortedList<T> extends LinkedList<T> {
      int intMethod(T integerObject){
          return integerObject;         // <--  "Cannot convert from T to int"
      }
}

删除类型参数,它工作得很好:

class SortedList extends LinkedList<Integer> {
      int intMethod(Integer integerObject){
          return integerObject;
      }
}
于 2011-02-06T07:35:52.363 回答
2

The problem is that you've declared Integer as a generic type parameter for the SortedList class. So when you refer to Integer as a parameter of the intMethod method, that means the type parameter, not the java.lang.Integer type which I suspect you meant. I think you want:

class SortedList extends LinkedList<Integer> {
    int intMethod(Integer integerObject){
        return integerObject;
    }
}

This way a SortedList is always a list of integers, which I suspect is what you were trying to achieve. If you did want to make SortedList a generic type, you would probably want:

class SortedList<T> extends LinkedList<T> {
    int intMethod(Integer integerObject){
        return integerObject;
    }
}
于 2011-02-06T07:36:05.087 回答