Java:泛型输入类型兼容性

时间:2017-08-26 04:38:26

标签: java generics

我是一名java初学者,我正在阅读这本书" Java是初学者的指南"和泛型主题。作者创建了以下泛型类:

// In this version of NumericFns, the type argument
// for T must be either Number, or a class derived
// from Number.
class NumericFns<T extends Number> {
    T num;
    // Pass the constructor a reference to
    // a numeric object.
    NumericFns(T n) {
        num = n;
    }

在这种情况下,类型参数 必须是数字或 Number的子类。

    // Return the reciprocal.
    double reciprocal() {
        return 1 / num.doubleValue();
    }
    // Return the fractional component.
    double fraction() {
        return num.doubleValue() - num.intValue();
    }
    // ...
}

并且作者说如果我们添加一个新方法来检查存储在两个通用对象中的数值的绝对值,如下所示:

// This won't work!
// Determine if the absolute values of two objects are the same.
boolean absEqual(NumericFns<T> ob) {
    if(Math.abs(num.doubleValue()) ==
            Math.abs(ob.num.doubleValue()) return true;
    return false;
}

用它写的解释是:

  

这里,标准方法Math.abs()用于获取每个数字的绝对值,       然后比较这些值。这种尝试的麻烦在于它只能用于       其他类型与调用对象相同的NumericFns对象。例如,如果       调用对象的类型为NumericFns<Integer>,则参数ob也必须是类型       NumericFns<Integer>。它不能用于比较NumericFns<Double>类型的对象,       例如。因此,这种方法不会产生一般的(即通用的)解决方案。

我无法理解为什么它不适用于所有不同类型。 请帮忙。

1 个答案:

答案 0 :(得分:3)

这是因为T中的absEqual(NumericFns<T> ob)与构造函数中的T相同(如果该方法属于同一个类)。这就是为什么如果使用NumericFns不同TInteger一次Doubleerror: incompatible types: NumericFns<Double> cannot be converted to NumericFns<Integer> ,则得到:

// This will work!
// Determine if the absolute values of two objects are the same.
boolean absEqual(NumericFns<? extends Number> ob) {
    if( Math.abs(num.doubleValue()) ==
            Math.abs(ob.num.doubleValue()) ) return true;
    return false;
}

相反,您可以使用:

[tblCategory registerForDraggedTypes:[NSArray arrayWithObject:@"public.text"]];
相关问题