I'm working on a Java project where I have an interface `A` with a method `calculate(T a, T b)`. I created classes `B` and `C` that implement this interface for `Double` and `Integer` types, respectively. However, I'm trying to call the `calculate()` method from another class `X` using arrays of type `Object[]`. The idea is to perform calculations on corresponding elements of two arrays, `V` and `U`. If the elements are `Integers`, I want to use the calculation method from class `C`; if they are `Doubles`, class `B`'s method should be used. I need to accumulate all local results from these calculations into a global result to return it to the calling class. I'm not clear if I should create a new class like `GlobalResult` that implements interface `A`, or if there's a better way to structure this since I can't change the caller's class. Any advice would be appreciated!
2 Answers
I think you're doing your best with a tricky situation! If you can't modify the calling class, using `serialize` with `instanceof` might end up being necessary. Just make sure your types are consistent in `V` and `U`. If you find you’re having lots of conditional checks, you might want to re-evaluate your approach for efficiency later on. But for now, it sounds like you’re on the right track!
Your pseudocode is a good start! To implement it in real code, one option is to use the `instanceof` operator to check the types like this:
```java
if (V[i] instanceof Double) {
globalRes += calculateB((Double) V[i], (Double) U[i]);
} else if (V[i] instanceof Integer) {
globalRes += calculateC((Integer) V[i], (Integer) U[i]);
}
```
However, I understand you might want to avoid `instanceof`. You could also look at using polymorphism to clean this up. If you can modify your design, consider creating a common interface that both `B` and `C` implement. This way, instead of manually checking types, you could just store instances of `A` in an array and call `calculate()` on them. For your current scenario, though, using `instanceof` seems like the way to go for efficiency!
I agree with you! Using `instanceof` can feel a bit clunky, but in this case, it seems to be the most straightforward solution given the constraints. Polymorphism is certainly cleaner if you're able to implement it later.

Thanks! I'll consider revising my approach if I continue to run into issues during implementation.