如何从用户定义类型的优先级队列中删除对象。

问题描述 投票:0回答:1

我的优先队列定义为

PriorityQueue< LRUCache > qu = new PriorityQueue<>(new Comp() );

在这里,LRUCache类有一个变量key和freq,基于此,我创建了比较器,如果我必须根据特定的key和freq从优先级队列中删除一个特定的对象,我怎么做呢?

qu.remove(new LRUCache(key , freq ) ) // like this or something better ??
java dictionary queue heap priority-queue
1个回答
1
投票

是的,你可以,但首先,覆盖 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;
        }
© www.soinside.com 2019 - 2024. All rights reserved.