I have an operator class that has some classes and methods in it that deals with mathematical operations. The operator class is generic and extends Number so my operations can be with ints, doubles, floats, etc.
public class OperatorClass<T extends Number>
In this class there is an abstract class that provides a method in which numbers are operated upon using the calculate method
abstract class Op<T extends Number> {
abstract T calculate(DataSet<? extends Number> ds);
}
There are multiple classes that extend Op like the AddOp for example:
class AddOp<T extends Number> extends Op<T>{
public T calculate(DataSet<? extends Number> ds) {
return ds.getLeft() + ds.getRight();
}
}
And my DataSet is just a data class that looks like this:
public class DataSet<T extends Number> {
private T left;
private T right;
public DataSet(T left, T right) {
this.left = left;
this.right = right;
}
public T getLeft() {
return left;
}
public T getRight() {
return right;
}
}
The problem I am having is that the line ds.getLeft() + ds.getRight() is not compiling because the Number abstract class cannot do a + operator. How do i get my DataSet to be a type of Number (like a wildcard class) so i can do math operations on it.
Any help would be appreciated
Thanks
Edit
So a workaround to the problem is that I used some if statements and then got the correct primitive datatype like so
Number result = null;
if(ds.getLeft().getClass().equals(Integer.class))
result = new Integer(ds.getLeft().intValue() + ds.getRight().intValue());
....
return (T) result;
You have to decide at what resolution you are going to add. In other words, are you calling
left.getInteger()orleft.getFloat()?There are a number of ways of solving this, but it really boils down to what you intend to do. If you want your numbers to truly remain objects, you cannot use the
+plus operator because that doesn’t work on objects. You need aleft.plus(right)style method call which returns a new number.If you don’t care about maintaining your numbers as objects during math exercises (perhaps they were just objects for the sake of collection storage or something) then you replace the
public T getLeft()withpublic long getLeft()and rely on the internal number’sleft.getLongValue()to do the conversion. Or you just expose the twoNumberobjects and allow the “external” user to do the appropriategetXxxValue()calls.