Use math operators on generic variables in a generic Java class

北城余情 提交于 2020-07-06 11:03:43

问题


I'm trying to write some code that will allow me to perform basic math operations on a "T extends Number" object instance. It needs to be able to handle any number type that is a subclass of Number.
I know some of the types under Number have .add() methods built in, and some even have .multiply() methods. 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. 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.


回答1:


What you will need to do is use the double value of the Number. However, this means that you cannot return the Number type.

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



回答2:


Java does not allow operators to be called on classes (so no +, -, *, /) you have to do the math as a primitive (I was going to show the code... but jjnguy beat me to it :-).



来源:https://stackoverflow.com/questions/4028358/use-math-operators-on-generic-variables-in-a-generic-java-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!