Java:使用泛型来实现可对各种数字进行运算的类 [英] Java: Using generics to implement a class that operates on different kinds of numbers

查看:259
本文介绍了Java:使用泛型来实现可对各种数字进行运算的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,假设我想编写一个对不同类型的数字进行运算的类,但是我不知道要使用哪种数字(即,整数,双精度数等).

So, let's say I want to write a class that operates on different kinds of numbers, but I don't a priori know what kind of numbers (i.e. ints, doubles, etc.) I will be operating on.

我想使用泛型为这种情况创建一个通用类.像这样:

I would like to use generics to create a general class for this scenario. Something like:

 Adder<Double> adder = new Adder<Double>();
 adder.add(10.0d, 10.0d);   // = 20.0d

但是,我无法实例化传递给我的Adder类的泛型类型!那么-该怎么办?

But, I cannot instantiate the generic type I pass in to my Adder class! So -- what to do?

推荐答案

呃,噢,-泛型不是C ++模板.由于类型擦除,示例中的Double甚至都不会显示到运行时系统.

Uh oh---generics are not C++ templates. Because of type erasure, the Double in your example won't even show through to the runtime system.

在您的特定情况下,如果您只是想将各种类型加在一起,是否可以建议方法重载?例如double add(double, double)float add(float, fload)BigDecimal add(BigDecimal, BigDecimal)

In your particular case, if you just want to be able to add various types together, may I suggest method overloading? e.g., double add(double, double), float add(float, fload), BigDecimal add(BigDecimal, BigDecimal), etc.

这篇关于Java:使用泛型来实现可对各种数字进行运算的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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