Java泛型算术 [英] Java generic arithmetic

查看:55
本文介绍了Java泛型算术的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一些Java类,这些类应与浮点数或双数一起使用(出于仿真目的,我需要同时支持这两种方法).这些类需要执行一些基本的算术运算,还需要使用三角函数(sin,cos,atan2).

I'm trying to create some Java classes, that should work with either float or double numbers (for simulation purposes I am required to support both). The classes need to do some basic arithmetic and also require use of trigonometric functions (sin, cos, atan2).

我试图做一个通用的方法.由于Java不允许泛型中的原始类型,而 MyClass< T扩展Number> 确实允许使用Double和Float,但是使基本的算法无法实现,因此我围绕Double和Float构建了包装类.但是,一旦我需要在一个通用类之一中实例化一个值,这种方法就会失败.

I tried to do a generic approach. As Java does not allow primitive types in generics and MyClass<T extends Number> does indeed allow Double and Float, but makes basic arithmetic impossible, I build a wrapper class around Double and Float. But this approach fails, as soon as I need to instantiate a value in one of the generic classes.

有没有一种干净的方法可以同时支持浮点数和双精度,而不必为每种类型复制所有代码?

Is there any clean way to support both float and double, without duplicating all the code for each type?

推荐答案

根据经验,如果您正在用Java进行核心数字工作,最好坚持使用基本类型.这意味着对于这种类型的工作来说,泛型是行不通的(但是对于许多其他用途来说当然是完美的).

From experience, if you're doing hardcore numerical work in Java, it's better to stick to primitive types. This means that generics are a no-go for this type of work (but of course are perfectly fine for many other uses).

有没有一种干净的方法可以同时支持浮点数和双精度,而不必为每种类型复制所有代码?

Is there any clean way to support both float and double, without duplicating all the code for each type?

您可以使用精度更高的方法来实现精度较低的方法:

You could implement the lower-precision method in terms of the higher-precision one:

public static double calc(double x, double y) {
   // do the calculation and return double
}

public static float calc(float x, float y) {
   return (float)calc((double)x, (double)y);
}

这篇关于Java泛型算术的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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