Java:自动记忆

2024-04-30 03:37:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码中有几个函数,在这些函数中使用记忆化是很有意义的(似乎甚至是强制性的)。在

我不想为每个函数分别手动实现。有没有什么方法(例如like in Python)我可以只使用一个注释或者做一些其他的事情,这样我就可以在我想要的地方自动地在那些函数上得到它?在


Tags: 方法记忆函数代码in地方手动事情
3条回答

我遇到了一个名为Tek271的记忆库,它看起来像您描述的那样使用注释来记忆函数。在

Spring3.1现在提供了一个^{} annotation,正是这样做的。在

As the name implies, @Cacheable is used to demarcate methods that are cacheable - that is, methods for whom the result is stored into the cache so on subsequent invocations (with the same arguments), the value in the cache is returned without having to actually execute the method.

我不认为有一个母语实现的记忆。在

但作为方法的装饰器,您可以很容易地实现它。你必须维护一个地图:地图的关键是参数,值是结果。在

对于单参数方法,这里是一个简单的实现:

Map<Integer, Integer> memoizator = new HashMap<Integer, Integer>();

public Integer memoizedMethod(Integer param) {

    if (!memoizator.containsKey(param)) {
        memoizator.put(param, method(param));
    } 

    return memoizator.get(param);
}

相关问题 更多 >