拆箱问题 [英] Unboxing issues
问题描述
我有一个扩展LinkedList类的类。
这里是代码的摘录:
I have a class that extends the LinkedList class. Here's an excerpt of the code:
class SortedList<Integer> extends LinkedList<Integer> {
int intMethod(Integer integerObject){
return integerObject;
}
}
预计会返回自动取消装箱的int值。但由于某种原因,编译器抛出一个错误,指出类型不兼容,并且所需类型为int,找到的类型为Integer。这在另一个班级完美无缺!是什么赋予了? :(
This is expected to return the auto-unboxed int value. But for some reason, the compiler throws an error that says that the types are incompatible and that the required type was int and the type found was Integer. This works in a different class perfectly fine! What gives? :(
推荐答案
这是因为你有<整数>
之后 SortedList
。
通常你使用 T
作为类型参数: class SortedList< T>
,但你使用 Integer
代替。也就是说,你做了整数
一个类型参数(隐藏 java.lang.Integer
)。
Usually you use T
for type parameters: class SortedList<T>
, but you used Integer
instead. That is, you made Integer
a type parameter (which shadows the java.lang.Integer
).
你的课程,就等同于
class SortedList<T> extends LinkedList<T> {
int intMethod(T integerObject){
return integerObject; // <-- "Cannot convert from T to int"
}
}
删除类型参数,它可以正常工作:
Remove the type parameter and it works just fine:
class SortedList extends LinkedList<Integer> {
int intMethod(Integer integerObject){
return integerObject;
}
}
这篇关于拆箱问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!