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.
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());
}
Java不允许在类上调用运算符(所以没有+, - ,*,/)你必须把数学作为一个原语(我打算显示代码......但是jjnguy打败了我:-) 。
你应该查看http://code.google.com/p/generic-java-math/ ,它解决了java中泛型算法的问题,甚至可能有你想要的几何函数。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.