How to Do Arithmetic Operations on the Number Baseclass

Using a generic class to perform basic arithmetic operations

No, there isn't a way to do this, or else it would be built into Java. The type system isn't strong enough to express this sort of thing.

C# numeric base class

You will have to resort to using overloading. A little like the Math class is doing with function like Math.Max where it support all numeric types.

The link proposed by CD is also resourceful.

Overloading arithmetic operators with inheritance in C++

It's difficult to delegate operator* (because it manufactures a new instance), but it's easy to delegate operator*= (because it works in-place and doesn't lead to slicing). So, just implement the former consistently in terms of the latter.

OpBase& OpBase::operator*=(const OpBase& other) {
// Actual logic goes here.
last *= other.last;
return *this;
}

// Could also be made a non-member with two parameters
OpBase OpBase::operator*(const OpBase& other) {
// Standard boilerplate.
OpBase ret(*this);
ret *= other;
return ret;
}

OpDerived& OpDerived::operator*=(const OpDerived& other) {
OpBase::operator*=(other);
// Additional logic specific to OpDerived goes here.
first *= other.first;
return *this;
}

// Could also be made a non-member with two parameters
OpDerived OpDerived::operator*(const OpDerived& other) {
// Standard boilerplate again.
OpDerived ret(*this);
ret *= other;
return ret;
}

Arithmetic element by element difference between 2 collections using Java Generics

Since Number does not provide any subtract method, you can't do it simply. The alternatives I can think of are:

  1. use the provided doubleValue() method, and return a double, but you could lose precision if the lists contain BigDecimal for example.
  2. have one method per available Number subclass, but it could create a lot of duplicated code...
  3. restrict the type to whatever makes sense (say double if precision does not matter too much or BigDecimal if it does), which is a subcase of (2).

Option 2 could be implemented like by replacing difference.add(currMinuend-subtrahend.get(i)); by difference.add(subtract(currMinuend, subtrahend.get(i)));

Then it's only a matter of writing 10 subtract methods:

private static int subtract(int a, int b) { return a - b; }
private static double subtract(double a, double b) { return a - b; }
private static BigDecimal subtract(BigDecimal a, BigDecimal b) { return a.subtract(b); }

etc.



Related Topics



Leave a reply



Submit