拆箱问题
我有一个扩展 LinkedList 类的类。 以下是代码摘录:
class SortedList<Integer> extends LinkedList<Integer> {
int intMethod(Integer integerObject){
return integerObject;
}
}
预计将返回自动拆箱的 int 值。但由于某种原因,编译器抛出一个错误,指出类型不兼容,所需的类型是 int,而找到的类型是 Integer。这在不同的班级中工作得很好!什么给? :(
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;
}
}
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? :(
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是因为
SortedList
之后有
。通常您使用
T
作为类型参数:class SortedList
,但您使用Integer
代替。也就是说,您将 Integer 设置为类型参数(它隐藏了 java.lang.Integer)。按照目前的情况,您的类相当于
删除类型参数,并且它工作得很好:
This is because you have
<Integer>
afterSortedList
.Usually you use
T
for type parameters:class SortedList<T>
, but you usedInteger
instead. That is, you madeInteger
a type parameter (which shadows thejava.lang.Integer
).Your class, as it stands, is equivalent to
Remove the type parameter and it works just fine:
问题在于您已将
Integer
声明为SortedList
类的泛型类型参数。因此,当您将Integer
引用为intMethod
方法的参数时,这意味着类型参数,而不是java.lang.Integer
类型。我怀疑你的意思是我认为你想要:这样
SortedList
始终是一个整数列表,我怀疑这就是你想要实现的目标。如果您确实想让SortedList
成为泛型类型,您可能需要:The problem is that you've declared
Integer
as a generic type parameter for theSortedList
class. So when you refer toInteger
as a parameter of theintMethod
method, that means the type parameter, not thejava.lang.Integer
type which I suspect you meant. I think you want: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 makeSortedList
a generic type, you would probably want: