I came across an interesting problem and was wondering if and how could this be done in Java:
Create a method which can memoize any function/method . The method has the following arguments : the method/function and the argument(s) for it.
For example let's say i have this method :
int addOne(int a) { return a + 1;}
and i call my memoization method two times with the same arguments : addOne and 5 for example, the first call should actually call the addOne method and return the result and also store that result for that given argument. The second time when i call it should know this has been called before and just look up the previous answer.
My idea would be to have something like a HashMap<Callable,HashMap<List<Objects>,Object>>
where you would store the previous answers and look them up later on.I think this can be somehow done with lambda expressions but i'm not that familiar with them.I'm not quite sure how to write this method and would appreciate some help.
Can this be done with this approach?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…