java - 泛型中的有界类型
问题描述
给出下面的示例,为什么我需要在 reciprocal() 中使用 doubleValue()(为此需要扩展 Number 类),因为 java 中有自动拆箱功能,它可以拆箱存储在 num 中的数字对象并可以计算倒数num 并返回一个双精度值?
class gen<T extends Number>{
T num ;
gen(T n ){
num = n ;
}
double reciprocal() {
return (1 / num.doubleValue()) ;
}
}
public class demo {
public static void main(String[] args) {
gen<Integer> ob = new gen<Integer>(5) ;
System.out.println(ob.reciprocal()) ;
}
}
另外,为什么我不能编写如下所示的相同代码?PS:以下代码显示 reciprocal() 方法中的错误:
class gen<T>{
T num ;
gen(T n ){
num = n ;
}
double reciprocal() {
return (1 / num) ;
// it shows error in the above step. it says "operator / is undefined
}
}
public class demo {
public static void main(String[] args) {
gen<Integer> ob = new gen<Integer>(5) ;
System.out.println(ob.reciprocal()) ;
}
}
解决方案
自动拆箱不是Number
该类的特性,它是它的一些子类(Integer
、Double
、Float
等)的特性。有许多子类Number
不具有此功能(例如,BigInteger
、BigDecimal
等...)。
由于您的第一个代码段中的泛型类型参数可以是扩展的任何类型Number
,它不一定具有自动拆箱功能,因此您必须告诉编译器如何转换T
为可以作为除法操作数的数字原始类型操作员。
在你的第二个片段中,T
没有界限,所以它可以是任何东西。/
它没有为任何任意类型定义的运算符。它是为数字操作数定义的。因此,编译器不能应用于/
以及1
何时num
是num
某种任意引用类型。
推荐阅读
- visual-studio - 查找 Visual Studio PATH/LIB 文件的问题
- python - 并行处理没有提高效率?
- android - 如何在 Jetpack compose 中制作 FlipCard 动画
- swift - 无法导入 EventKitUI。错误无法构建 Objective-C 模块
- c++ - 在 dll 中调用函数,同时在其中包含 dll/lib 文件
- coq - 为什么在相当简单的情况下无法进行案例分析
- python - 输出到终端和输出到文件得到不同的结果
- rest - 即使在 GET 请求中,我们也可以使用 SCIM 属性的“请求”可返回属性吗?
- routes - 如何在动态 nuxt.js 路由中的另一个 _slug 目录中使用 _slug?
- assembly - 包括另一个文件的程序集不起作用