我的优先队列定义为
PriorityQueue< LRUCache > qu = new PriorityQueue<>(new Comp() );
在这里,LRUCache类有一个变量key和freq,基于此,我创建了比较器,如果我必须根据特定的key和freq从优先级队列中删除一个特定的对象,我怎么做呢?
qu.remove(new LRUCache(key , freq ) ) // like this or something better ??
是的,你可以,但首先,覆盖 equals()
在你 LRUCache
类,因为PriorityQueue在内部使用它来寻找对象以删除它。
private int indexOf(Object o) {
if (o != null) {
final Object[] es = queue;
for (int i = 0, n = size; i < n; i++)
if (o.equals(es[i]))
return i;
}
return -1;
}
你 LRUCache
类与 equals()
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || obj.getClass() != this.getClass())
return false;
LRUCache cache = (LRUCache) obj;
return key.equals(cache.key) && freq == cache.freq;
}