缓存集合式集合

时间:2011-05-10 10:19:07

标签: java caching collections set

我正在尝试使用类似集合的要求来缓存许多类似的值。不幸的是Set<?>只允许我检查一个元素是否存在于内部 - 它不会将现有元素返回给我。我想做的是:

Element e = receiveSomeElement();
e = elements.cache(e);
// now e is either the original e, or one that was already in the cache
doSomeWorkOn(e);

我可能会使用SortedSet并获得.subSet(e, e)来模拟它,但似乎浪费时间来保持整理的设置。我也可以使用HashMap<Element, Element>并存储与键和值相同的引用,但这看起来同样很脏......

有没有更好的方法呢?

5 个答案:

答案 0 :(得分:3)

如果您正在使用HashSet,那么底层实现实际上仍然使用HashMap,因此我建议您使用HashMap。

答案 1 :(得分:1)

您可能希望查看Apache Collections提供的LRUMap。它的行为类似于地图,但限制了大小,以便在处理大量数据时事情不会失控。我还写了一篇关于如何在LRUMap周围添加一些簿记以使其在未使用时也缩小的文章:Blog post: Caching without Crashing

答案 2 :(得分:0)

下面是基本的缓存实现,这里也使用了HashMap Caching implementation

答案 3 :(得分:0)

您可能希望使用LinkedHashMap,以便实施简单的驱逐政策。

Map<Element, Element> cache = new LinkedHashMap<Element, Element>(16, 0.7, true){
    protected boolean removeEldestEntry(Map.Entry<Element, Element> eldest) {
        return size() > MAX_SIZE;
    }

    public Element get(Object key) {
        Element element = super.get(key);
        // put if not present.
        if (element == null) {
            element = (Element) key;
            super.put(element, element)
        }
        return element;
    }
};

这样你可以调用get(e),如果它不存在,它将返回e。根据需要删除最近最少使用的条目,将其限制为MAX_SIZE。

答案 4 :(得分:0)

这是一个解决方案。没有声称我会像这样解决它。将其视为如何获取集合中特定元素的演示。

// Create a temporary copy of the cache.
Set<Element> matches = new HashSet<Element>(cache);

// Remove all elements that don't equal the soughtElement.
matches.retainAll(Collections.singleton(soughtElement));

if (matches.isEmpty()) {
    // ... not found
} else {
    Element found = matches.iterator().next();
    // ...
}