【发布时间】:2012-10-25 10:07:34
【问题描述】:
简介
我使用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)));
}
}
EDIT它成功通过了两个测试。
它通过了第一个测试。它无法在
上抛出AssertExceptionassertTrue(cache.peekFirst() == 1);第二次测试,
【问题讨论】:
-
在构造函数中设置静态变量不是好的做法。但这不是您的问题的一部分。
-
您如何确定队列中没有任何内容?
-
CachedClass 是否覆盖等于?