通用类型扩展数量,计算 [英] Generic type extending Number, calculations

查看:67
本文介绍了通用类型扩展数量,计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用一个方法创建了一个数学运算的接口,计算出各种参数的数量。

pre $ public interface MathOperation {
public< T extends Number> T计算(T ... args);
}

这个类的简单实现不起作用:

  private class Sum implements MathOperation {
@Override
public< T extends Number> T calculate(T ... args){
return args [0] + args [1];


$ / code $ / pre

问题是:

 二元运算符的错误操作数类型'+'
第一种类型:T
第二种类型:T
其中T是类型变量:
T extends在方法< T> calculate(T ...)中声明的数字

我试图实现的是一个简单的类,以两个双打为例,并返回Double。

有没有可能实现这一点?

解决方案

+ 不能应用于扩展数字 new Integer(5)+ new Integer(5)因为自动装箱而起作用。您将必须查看参数的运行时类型并相应地执行操作。



以下行的内容:

  private class Sum实现MathOperation {
@Override
public< T extends Number> T计算(Class< T> clazz,T ... args){
if(clazz.equals(Integer.class))
{
return Integer.class.cast(args [0 ])+ Integer.class.cast(args [1]);
} else(....)
}
}


I've made an interface of math operation with one method, calculate, taking various number of arguments

public interface MathOperation {
    public <T extends Number> T calculate(T... args);
}

There's also simple implementation of this class, which does not work:

private class Sum implements MathOperation {
    @Override
    public <T extends Number> T calculate(T... args) {
        return args[0] + args[1];
    }
}

The problem is:

bad operand types for binary operator '+'
  first type:  T
  second type: T
  where T is a type-variable:
    T extends Number declared in method <T>calculate(T...)

What I'm trying to achieve is a simple class, taking for example two Doubles and returning Double as well.

Is there possibility to achieve this?

解决方案

+ cannot be applied to types that extend Number. new Integer(5) + new Integer(5) works because of autoboxing. You will have to look at the runtime type of args and do the operation accordingly.

Something on the lines of:

private class Sum implements MathOperation {
    @Override
    public <T extends Number> T calculate(Class<T> clazz, T... args) {
         if (clazz.equals(Integer.class))
         {
             return Integer.class.cast(args[0]) + Integer.class.cast(args[1]);
         } else (....) 
    }
}

这篇关于通用类型扩展数量,计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆