首页 > 解决方案 > 泛型中的有界类型

问题描述

给出下面的示例,为什么我需要在 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()) ;
    }

}

标签: javagenericsbounded-types

解决方案


自动拆箱不是Number该类的特性,它是它的一些子类(IntegerDoubleFloat等)的特性。有许多子类Number不具有此功能(例如,BigIntegerBigDecimal等...)。

由于您的第一个代码段中的泛型类型参数可以是扩展的任何类型Number,它不一定具有自动拆箱功能,因此您必须告诉编译器如何转换T为可以作为除法操作数的数字原始类型操作员。

在你的第二个片段中,T没有界限,所以它可以是任何东西。/它没有为任何任意类型定义的运算符。它是为数字操作数定义的。因此,编译器不能应用于/以及1何时numnum某种任意引用类型。


推荐阅读