I'm writing a class which will make time consuming calculations on parametres stored in a list of MyObjects. Since I wanted to have easy access to a number of List's features, I decided to write it extending a list type (an alternative would be to have a List as one of the fields in my class and rewrite all methods I'm going to use, but it looks like an overcomplication). Since the calculations are pretty complex and time consuming, while the result depends solely on the stored parameters (no time influence, no hidden dependencies, etc), I decided to cache the result. So my code looks more or less like this:
public class Calculator extends ArrayList<MyObject> {
private double Result = Double.NaN;
public double getResult() {
if (Double.isNaN(Result)) {
Result = CalculateResult();
}
return Result;
}
}
This way, when the method getResult() is called for the first time it calculates the result, stores it, and then reuses during subsequent calls.
Now, the list's contents can be modified with various methods, and many modifications should clear the cache. To achieve this, normally I would write something like:
public void add(MyObject newvalue) {
super.add(newvalue);
Result = Double.NaN;
}
However, it does not work, because "super" refers to the generic ArrayList class, so the compiler produces a type error.
An obvious trick on my level would be to create an interim class, which would implement ArrayList of MyObject and make Calculator extend this interim class:
public class MyArrayList extends ArrayList<MyObject> {
}
public class Calculator extends MyArrayList {
}
But it looks like an overcomplication again. Isn't there a more elegant method to achieve this result? Or perhaps, is there a mechanism similar to trigger in SQL, which would force my class clear the cache whenever any modification is made to the List?