java通用添加 [英] java generic addition
本文介绍了java通用添加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
I'm attempting implement the add method mentioned in the Generic sparse matrix addition question
class Matrix<T extends Number>
{
private T add(T left, T right)
{
if (left instanceof Integer)
{
return new Integer(((Integer)left).intValue() + ((Integer)right).intValue());
}
}
找到的编译器错误java.lang.Integer必需的T
在我返回一个新的整数的行。我不确定自从T扩展Number并且Integer是Number的子类时我缺少的是什么。
The compiler errors with found java.lang.Integer Required T
at the line where I return a new Integer. I'm not sure what I'm missing since T extends Number and Integer is a subclass of Number.
推荐答案
编译器不会不要让你这样做,因为 T
可能是其他一些类,比如 Double
。
从 instanceof
检查中您知道 T
是整数
,但编译器不会。
The compiler doesn't let you do this because T
might be some other class, such as Double
.
You know that T
is Integer
from the instanceof
check, but the compiler doesn't.
这篇关于java通用添加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文