英文:
How to remove an object from priority queue of user defined type
问题
我将优先队列定义为:
PriorityQueue<LRUCache> qu = new PriorityQueue<>(new Comp());
在这里,LRUCache
类具有基于 key
和 freq
的变量,我基于这些创建了比较器。
如果我想要从优先队列中移除特定的对象,根据特定的 key
和 freq
,应该如何操作:
qu.remove(new LRUCache(key, freq)) // 像这样还是有更好的方法??
英文:
i have my priority queue defined as
PriorityQueue< LRUCache > qu = new PriorityQueue<>(new Comp() );
here LRUCache class has the variable key and freq based on which i created the Comparator.
if i have to remove a particular object from priority queue based on certain key and freq
how can i do that
qu.remove(new LRUCache(key , freq ) ) // like this or something better ??
答案1
得分: 1
是的,你可以这样做,但首先需要在你的LRUCache
类中添加equals()
方法,因为PriorityQueue
在内部使用它来查找要移除的对象。
也就是说,这是从PriorityQueue
中的indexOf(...)
代码,该代码被remove(...)
方法调用:
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()
方法:
equals(...)
方法将检查以下内容:
1- 检查参数obj
是否与当前对象使用this关键字相等,然后返回true。
2- 检查参数obj
是否为null
或者是否与当前类不是同一类,如果是则返回false。
3- 否则,参数obj
将是有效且为相同类型,因此将其转换为目标类,即这里的LRUCache
类,并根据需要检查类中的任何属性,这里是key
和freq
。
@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;
}
英文:
Yes, you can but first, the equals()
method in your LRUCache
class because the PriorityQueue
uses it internally for finding the object to remove it.
i.e this is the indexOf(...)
code from the PriorityQueue
which called be remove(...)
method
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;
}
, Just add to your LRUCache
class the equals()
The equals(...)
method will check the following:
1- Check if the obj parameter equals the current object with this keyword then return true
2- Check if the obj parameter equals null or not the same class "invalid state" then return false
3- Otherwise the obj parameter will be valid and the same type, so cast to the target class which is here LRUCache
, and check with whatever properties in the class based on your needs, here they are key
and freq
@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;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论