简体   繁体   English

对通用Java类中的泛型变量使用数学运算符

[英]Use math operators on generic variables in a generic Java class

I'm trying to write some code that will allow me to perform basic math operations on a "T extends Number" object instance. 我正在尝试编写一些代码,允许我在“T extends Number”对象实例上执行基本的数学运算。 It needs to be able to handle any number type that is a subclass of Number . 它需要能够处理任何数字类型,它是Number的子类。
I know some of the types under Number have .add() methods built in, and some even have .multiply() methods. 我知道Number下的一些类型有内置的.add()方法,有些甚至有.multiply()方法。 I need to be able to multiply two generic variables of any possible type. 我需要能够将任何可能类型的两个泛型变量相乘。 I've searched and searched and haven't been able to come up with a clear answer of any kind. 我进行了搜索和搜索,但未能提出任何明确的答案。

public class Circle<T extends Number> {

private T center;
private T radius;
private T area;

// constructor and other various mutator methods here....

/**
  The getArea method returns a Circle
  object's area.
  @return The product of Pi time Radius squared.
*/
public Number getArea() {
    return  3.14 * (circle.getRadius()) * (circle.getRadius());      
}  

Any help would be much appreciated. 任何帮助将非常感激。 Generics are the most difficult thing I've encountered in learning Java. 泛型是我在学习Java时遇到的最困难的事情。 I don't mind doing the leg work because I learn better that way, so even a strong point in the right direction would be very helpful. 我不介意做腿部工作,因为我以这种方式学得更好,所以即使是正确方向的强点也会非常有帮助。

What you will need to do is use the double value of the Number . 您需要做的是使用Number的double值。 However, this means that you cannot return the Number type. 但是,这意味着您无法返回Number类型。

public double getArea()
{
    return  3.14 * 
            (circle.getRadius().doubleValue()) * 
            (circle.getRadius().doubleValue());      
}  

Java不允许在类上调用运算符(所以没有+, - ,*,/)你必须把数学作为一个原语(我打算显示代码......但是jjnguy打败了我:-) 。

你应该查看http://code.google.com/p/generic-java-math/ ,它解决了java中泛型算法的问题,甚至可能有你想要的几何函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM