介绍
我使用ArrayDeque
以下 Generics
解决方案实现了一个带有 LRU 策略的简单缓存:
public class Cache<T> extends ArrayDeque<T> implements Serializable {
private static final long serialVersionUID = 1L;
private int MAX_SIZE;
public Cache(int maxSize) {
MAX_SIZE = maxSize;
}
public void store(T e) {
if (super.size() >= MAX_SIZE) {
this.pollLast();
}
this.addFirst(e);
}
public T fetch(T e) {
Iterator<T> it = this.iterator();
while (it.hasNext()) {
T current = it.next();
if (current.equals(e)) {
this.remove(current);
this.addFirst(current);
return current;
}
}
return null;
}
}
问题
当我实例化类并推送一个元素时,
Cache<CachedClass> cache = new Cache<CachedClass>(10);
cache.store(new CachedClass());
此时队列不包含任何内容。
为什么会这样?
观察
顺便说一句,CachedClass
覆盖了方法.equals()
。
测试
public class CacheTest {
@Test
public void testStore() {
Cache<Integer> cache = new Cache<Integer>(3);
cache.store(1);
assertTrue(cache.contains(1));
cache.store(2);
cache.store(3);
cache.store(4);
assertEquals(cache.size(), 3);
}
@Test
public void testFetch() {
Cache<Context> cache = new Cache<Context>(2);
Context c1 = new Context(1);
Context c2 = new Context(2);
cache.store(c1);
cache.store(c2);
assertEquals((Context) cache.peekFirst(), (new Context(2)));
Context c = cache.fetch(c1);
assertTrue(c == c1);
assertEquals(cache.size(), 2);
assertEquals((Context) cache.peekFirst(), (new Context(1)));
}
}
编辑它成功通过了两个测试。
它通过了第一次测试。它失败
AssertException
了assertTrue(cache.peekFirst() == 1);
第二次测试,